206. Reverse Linked List

2017-09-28  本文已影响0人  namelessEcho

100篇啦!!!

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null)return head;
        ListNode dummy = new ListNode(0);
        ListNode pre = dummy;
        dummy.next=head;
        ListNode p1 = head ;
        ListNode p2 = head.next;
        while(p2!=null)
        {
            p1.next= p1==head?null:pre;
            pre=p1;
            p1=p2;
            p2=p2.next;
        }
        // last operation 
        p1.next=pre;
        dummy.next=p1;
        return dummy.next;
       
    }
}
上一篇 下一篇

猜你喜欢

热点阅读