Reverse a singly linked list.java
click to show more hints.node
Hint: A linked list can be reversed either iteratively or recursively. Could you implement both?python
時間 O(N) 空間 O(N) 遞歸棧空間指針
基本遞歸code
public class Solution { ListNode newHead; public ListNode reverseList(ListNode head) { reverse(head); return newHead; } private ListNode reverse(ListNode n){ if( n == null || n.next == null){ newHead = n; } else { ListNode prev = reverseList(n.next); prev.next = n; } return n; } }
時間 O(N) 空間 O(1)遞歸
基本迭代it
javaio
public class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode p1 = head; ListNode p2 = p1.next; while(p2 != null){ ListNode tmp = p2.next; p2.next = p1; p1 = p2; p2 = tmp; } head.next = null; return p1; } }
pythonfor循環
class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ p1 = None p2 = head while(p2 is not None): tmp = p2.next p2.next = p1 p1 = p2 p2 = tmp return p1
Reverse a linked list from position m to n. Do it in-place and in one-pass.class
For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return
1->4->3->2->5->NULL
.Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
時間 O(N) 空間 O(1)
技巧在於記錄下這麼幾個變量:dummyHead、子鏈反轉前的頭節點,子鏈反轉前頭節點前面一個節點,子鏈反轉過程當中的當前節點,子鏈反轉過程當中的下一個節點,這五個指針。先跳過前m個節點,而後初始化好這五個指針後,用I中的方法反轉鏈表。完成了第n個節點的反轉後,將子鏈反轉前的頭節點的next設爲子鏈反轉過程當中的下一個節點,將子鏈反轉前頭節點前面一個節點的next設爲子鏈反轉過程當中的當前節點。因爲設置了dummyhead,咱們全部的反轉操做都是不包含頭節點的,因此直接返回dummyhead的next就好了。
跳過前m個節點的for循環要從1開始,由於咱們要保證head是第m-1個元素,若是m=1則不動。
public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(head == null || head.next == null) return head; ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; for(int i = 1 ; i < m; i++){ head = head.next; } ListNode headOfSubList = head.next; ListNode nodeBeforeHead = head; ListNode nextNode = head.next.next; ListNode currNode = head.next; for(int i = m; i < n ; i++){ ListNode tmp = nextNode.next; nextNode.next = currNode; currNode = nextNode; nextNode = tmp; } headOfSubList.next = nextNode; nodeBeforeHead.next = currNode; return dummy.next; } }