leetcode 206: Reverse Linked List

Reverse Linked List

Total Accepted: 8021 Total Submissions: 23499

Reverse a singly linked list.


[思路]

1. recursion   2  iteration

[CODE]

 1 recursion

/**
 * 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 null;
        if(head.next==null) return head;
        
        ListNode p = head.next;
        ListNode n = reverseList(p);
        
        head.next = null;
        p.next = head;
        return n;
    }
}

2. iteration

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
 
 // 1 <-2 3
public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null) return head;
        
        ListNode pre = head;
        ListNode p = head.next;
        pre.next = null;
        ListNode nxt;
        while(p!=null) {
            nxt = p.next;
            p.next = pre;
            pre = p;
            p = nxt;
        }
        return pre;
    }
}





你可能感兴趣的:(leetcode)