leetcode-206 反转链表
生活随笔
收集整理的這篇文章主要介紹了
leetcode-206 反转链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
描述如下:
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
方法一:原地反轉
數據結構如下
struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};
ListNode* reverseList(ListNode* head) {ListNode *new_head = NULL;while(head) {ListNode *p = head->next;head->next = new_head;new_head = head;head = p;}return new_head;
}
方法二:遞歸反轉
n1–>n2–>…–>n(k)–>n(k+1)–>…–>n(n)
加入n(k+1)之后的已經全部反轉完成
n1–>n2–>…–>n(k)–>n(k+1)<–…<–n(n)
那么我們想要讓n(k+1)–>n(k),可以如下方式
n(k)->next->next = n(k)
當然針對n1,我們需要將n1的下一個指向為空
ListNode* reverseList(ListNode* head) {if(head == NULL || head->next == NULL) return head;ListNode *p = reverseList(head->next);head -> next -> next = head;head -> next = NULL;return p;
}
總結
以上是生活随笔為你收集整理的leetcode-206 反转链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 想问一部电影的名字
- 下一篇: leetcode-92 反转链表II