结构体定义
typedef struct node{
int data;
struct node *next;
}Node, *LinkList;
一、新建链表法
运用头插法将原链表中的节点复制到新链表中。原链表中的最后一个节点到新链表的第一个节点,以此类推,得到反转后的链表。
struct node* reverseList(LinkList head){
Node* Newhead;//定义一个头节点
Newhead = (Node*)malloc(sizeof(Node));
Node *p = head, *q, *n; //p指向原链表的节点,q为临时节点,n为新链表中的节点
n = Newhead;
n->next = NULL;
while(p) {
q = p->next;//临时节点存p节点的下一个
p->next = n->next;
n->next = p;//
p = q;
}
return Newhead->next;
}
二、三指针法
定义三个指针,从头遍历,三个指针分别指向三个节点。反转前两个节点,即使第二个节点指向第一个节点,然后依次向后移动指针,知道第二个指针指向空时停止。
struct node* reverseList(LinkList head){
Node *p,*q,nexttmp;
p = NULL;
q = head;
nexttmp = NULL;
while(q){
nexttmp = q->next; //将q指向的下一个保存在nexttmp中
q->next = p; //反转
p = q;
q = nexttmp; //指针向后移动
}
return p;
}