05 August 2008
Reverse a singly linked list.
Example:
1
2
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
翻转一个单向链表,用递归和迭代的办法各实现一下。递归的办法;迭代的办法就是遍历每个结点然后把该节点的赋值为之前链表结点的next,然后把该结点的next赋值为之前链表的结点即可。
Time:都是O(n);Space:递归是O(n),迭代是O(1)。


(http://www.cnblogs.com/keeya/p/9218352.html)
遍历法就是在链表遍历的过程中将指针顺序置换
先上代码:
1
2
3
4
5
6
7
8
9
10
11
public static Node reverseList(Node node) {
  Node pre = null;
  Node next = null;
  while (node != null) {
      next = node.next;
      node.next = pre;
      pre = node;
      node = next;
  }
  return pre;
}
依旧是1->2->3->4
迭代的过程:
Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next
// Now change next of current
// This is where actual reversing happens
curr->next = prev
// Move prev and curr one step forward
prev = curr
curr = next

递归的过程
1) Divide the list in two parts - first node and rest of the linked list.
2) Call reverse for the rest of the linked list.
3) Link rest to first.
4) Fix head pointer

迭代
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode prev = null; // 前一个节点从null开始
        ListNode curr = head; // 当前节点从第一个节点开始
        
        while (curr != null) {
            ListNode temp = curr.next; // 第一步,临时变量记住当前节点的下一个
            curr.next = prev; // 第二步,将当前节点的下一个指向前一个
            prev = curr; //第三步,将前一个指针向后移动一步
            curr = temp; // 第四步,将当前指针往后移动一步
        }
        
        return prev; // 最后返回prev在最后一个节点处,此时curr在最后一个节点后面的null处
    }
}
递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
	public ListNode reverseList(ListNode head) {
		if (head == null || head.next == null) {
			return head;
		}
		ListNode result = reverseList(head.next);//逐步递归到最后两个结点
				
		//现在开始翻转两个结点,并“归”回去
		head.next.next = head;
		head.next = null;
		return result;
	}
}