1. 程式人生 > >206. Reverse Linked List (轉置單鏈表)

206. Reverse Linked List (轉置單鏈表)

Reverse a singly linked list.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?


解法一:(遞迴)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverse(ListNode p, ListNode q) {
		ListNode r = q.next;
		q.next = p;
		if (r == null)
			return q;
		else {
			return reverse(q,r);
		}
	}
	
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null)
			return head;
		ListNode temp = head.next;
		head.next = null;
		return reverse(head,temp);
    }
}
解法二:(迴圈)
/**
 * Definition for singly-linked list. public class ListNode { int val; ListNode
 * next; ListNode(int x) { val = x; } }
 */
public class Solution {

	public ListNode reverseList(ListNode head) {
		
        if(head==null)
        return head;
        ListNode p = head.next,q=null;
        head.next = null;
        while(p!=null){
            q=p.next;
            p.next=head;
            head=p;
            p=q;
        }
        return head;
    }
}


Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?