美文网首页
206. Reverse Linked List

206. Reverse Linked List

作者: namelessEcho | 来源:发表于2017-09-28 16:57 被阅读0次

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;
       
    }
}

相关文章

网友评论

      本文标题:206. Reverse Linked List

      本文链接:https://www.haomeiwen.com/subject/ankvextx.html