头插法建立单链表
伪代码
/*头插法建立单链表
可用于对单链表的逆转*/
typedef struct Lnode{
ElemType data;
Lnode * next;
} *LinkList;
LinkList List_HeadInsert(LinkList &L){
Lnode *p;
int x;
L = (LinkList)malloc(sizeof(Lnode));
L->next = null;
scanf("%d",&x);
while(x!=9999){
s = (Lnode*)malloc(sizeof(Lnode));
s->data = x;
s->next = L->next;
L-> next = s;
scanf("%d",&x);
}
return L;
}
对带有头结点的单链表进行逆转
对原有单链表进行顺序遍历并且将遍历的结果使用头插法建立到新的单链表中。
伪代码
//单链表进行转置
//伪代码
LinkList M;
M = (LinList)malloc(sizeof(Lnode));
LinkList List_transpose(LinkList &L, LinkList &M){
Lnode *p;
Lnode *q;
p = L->next;
while(p!=null){
q = (Lnode*)malloc(sizeof(Lnode));
q.data = p.data;
q.next = M->next;
M->next = q;
p = p->next;
}
return M;//返回转置后的单链表
}
不使用外部的存储单元,只进行指针的转换进行单链表的逆转
/* 实现单链表的逆转 */
LinkList Funct(LinkList Head){
LinkNode * Pointer, Back, Next;
Back = Head;
Pointer = Back->Next;
Back->Next = Null;
Next = Pointer->Next;
Pointer->Next = Back;
Back = Pointer;
Pointer = Next;
while(Pointer->Next !=Null){
Next = Pointer-> Next;
Pointer ->Next = Back;
Back = Pointer;
Pointer = Next;
}
Pointer -> Next = Back;
Head = Pointer;
return Head;
}