Leetcode 206. Reverse Linked List
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 206. Reverse Linked List
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Similar Questions?
Reverse Linked List II?Binary Tree Upside Down?Palindrome Linked List?
思路:鏈表反轉。
解法一:迭代。
添加頭節點(推薦):不斷將當前元素start插入dummy和dummy.next之間,實現反轉。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode reverseList(ListNode head) { 11 if(head == null) return head; 12 ListNode dummy = new ListNode(0); 13 dummy.next = head; 14 ListNode pre = head, start = head.next; 15 while(start != null) { 16 pre.next = start.next; 17 start.next = dummy.next; 18 dummy.next = start; 19 start = pre.next; 20 } 21 return dummy.next; 22 } 23 }?
不添加頭節點:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode reverseList(ListNode head) { 11 ListNode p0, p1; 12 p0 = null; 13 p1 = head; 14 while(p1 != null) {//確保p1不為空 15 ListNode p2 = p1.next; 16 p1.next = p0; 17 p0 = p1; 18 p1 = p2; 19 } 20 return p0; 21 } 22 }解法二:遞歸。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode reverseList(ListNode head) { 11 if(head == null || head.next == null) return head;//這個判斷很重要 12 ListNode p1 = head.next; 13 ListNode p0 = reverseList(p1); 14 p1.next = head; 15 head.next = null; 16 return p0; 17 } 18 }Next challenges:?
轉載于:https://www.cnblogs.com/Deribs4/p/8406523.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Leetcode 206. Reverse Linked List的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 海华模组:WIFI、BT、SoC模组列表
- 下一篇: 缓存(Cache)管理 ---- 系列