LeetCode---206. 反轉連結串列
阿新 • • 發佈:2018-11-10
題目來源:
https://leetcode-cn.com/problems/reverse-linked-list/description/
題目描述:
演算法描述:該題可以使用遞迴法和非遞迴法兩種
非遞迴法:
從前向後遍歷原連結串列,將每一個連結串列頭插到新連結串列上
程式碼如下:
struct ListNode* reverseList(struct ListNode* head) { struct ListNode *p, *newHead=NULL; while (head) { p=head; head=head->next; p->next=newHead; newHead=p; } return newHead; }
遞迴法:
1.要注意到異常情況(連結串列為空或只有一個)直接返回,不需要反轉
2.當前需要反轉的連結串列有N個結點時,可以先將除第一個元素外的剩下N-1個元素先反轉,再把第一個元素插入到剩下連結串列的末尾。再將問題往下細分,直到遇到空節點。
程式碼如下:
struct ListNode* reverseList(struct ListNode* head) { //如果連結串列為空或者連結串列中只有一個元素 if(head == NULL || head->next == NULL){ return head; } //先反轉後面的連結串列,走到連結串列的末端結點 struct ListNode* newhead = reverseList(head->next); //再將當前節點設定為後面節點的後續節點 head->next->next = head; head->next = NULL; return newhead; }