[데이터 구조] 단일 체인 표 의 초기 화 및 연산 작업
23759 단어 데이터 구조
#include
#include
#include
using namespace std;
//
typedef struct LNode{
int data;
struct LNode *next;
}LNode, *LinkList;
bool InsertPriorNode(LinkList &L,LNode *p, LNode *s);
bool InsertNextNode(LNode *p, int e);
LNode * GetElem(LinkList L, int i);
//
bool InitList(LinkList &L){
L = (LNode *)malloc(sizeof(LNode));
if(L == NULL){
return false;
}
L->next = NULL;
L->data = 3;
return true;
}
//
bool ListInsert(LinkList &L, int i, int e){
LNode *p = L;
int j = 0;
while(p != NULL && j < i-1){
p = p->next;
j++;
}
if(p == NULL) return false;
return InsertNextNode(p,e);
}
//
bool InsertNextNode(LNode *p, int e){
if(p == NULL){
return false;
}
LNode *s = (LNode *)malloc(sizeof(LNode));
if(!s){
return false;
}
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
//
bool InsertPriorNode(LinkList &L,LNode *p, LNode *s){
if(p == NULL || s == NULL){
return false;
}
s->next = p->next;
p->next = s;
swap(p->data, s->data);
return true;
}
//
void PrintList(LinkList L){
LNode *p;
p = L;
p = p->next;
while(p!=NULL){
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
//
void PrintNode(LNode *p){
if(!p){
cout<<"NULL"<<endl;
}
cout<<p->data<<endl;
}
//
LNode * GetElem(LinkList L, int i){
if(i == 0){
return L;
}
if(i < 1) return NULL;
int j = 0;
LNode *p = L;
while(p && j<i){
p = p->next;
j++;
}
return p;
}
//
LNode * LocateElem(LinkList L, int e){
LNode *p = L->next;
while(p && p->data != e)
p = p->next;
return p;
}
//
int length(LinkList L){
LNode *p = L->next;
int len = 0;
while(p){
p = p->next;
len++;
}
return len;
}
//
LinkList List_TaiInsert(LinkList &L){
int x;
cin>>x;
LNode *r;
r = L;
while(x!=-1){
InsertNextNode(r, x);
r = r->next;
cin>>x;
}
r->next = NULL;
}
// , , next
LinkList reverseList(LinkList &L){
LNode *p = L->next;
LNode *newL = (LNode *)malloc(sizeof(LNode));
newL->next = NULL;
while(p){
int e = p->data;
LNode *s = (LNode *)malloc(sizeof(LNode));
if(!s) return NULL;
s->data = e;
s->next = newL->next;
newL->next = s;
p = p->next;
}
L = newL;
return L;
}
int main() {
LinkList L;
InitList(L);
List_TaiInsert(L);
PrintList(L);
reverseList(L);
PrintList(L);
return 0;
}