方法一 : 從第二個結點開始,把之後的每個結點都插入到第一個結點之後,最後在把第一個結點挪
到表尾 , 該方法中類似於鏈表頭插法
struct stu *reserve(struct stu *head)
{
struct stu *p,*q;
p=head->next;
while(p->next!=NULL)
{
q=p->next;
p->next=q->next;
q->next=head->next;
head->next=q;
}
p->next=head;
head=p->next->next;
p->next->next=NULL;
return head;
方法二 :利用三個指針,在原來的基礎上進行逆序。這種方法比較實用,效率也高
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *ReverseList(ListNode *head){
ListNode *pre, *cur, *net;//前驅,中間,後繼節點。
pre = head;
cur = pre->next;
while (cur){
net = cur->next;
cur->next = pre;
pre = cur;
cur = net;
}
//這裏翻轉完成之後起初的頭結點就是尾節點了。所以
head->next = NULL;
*head = p1;
return head;
}
總結:
方法一中需要創建一個新的鏈表,把遍歷的節點存到該新的鏈表中
方法二是在原鏈表中進行操作,在空間上要優於方法二