LeetCode206:Reverse Linked List
生活随笔
收集整理的這篇文章主要介紹了
LeetCode206:Reverse Linked List
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Reverse a singly linked list.
分別用迭代和遞歸實現
struct ListNode {int val;struct ListNode *next; };迭代實現:
struct ListNode* reverseList(struct ListNode* head) {struct ListNode *pre = NULL;struct ListNode *cur = head;while( cur != NULL ){struct ListNode *after = cur->next;cur->next = pre;pre = cur;cur = after;}return pre; }遞歸實現:
1)如果head為空,或者只有head這一個節點,return head即可;
2)先遍歷head->next為首的鏈表,得到一個頭結點newHead;
3)把head賦值給head->next->next, head->next為空;
4)返回newHead。
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; }?
轉載于:https://www.cnblogs.com/evansyang/p/5446678.html
總結
以上是生活随笔為你收集整理的LeetCode206:Reverse Linked List的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVAWEB开发之JSP、EL、及会话
- 下一篇: 动态分配数组(new)和用随机数赋值(r