leetcode 206. Reverse Linked List

2387 ワード

leetcode 206. Reverse Linked List
タイトル
Reverse a singly linked list.
解1
/**
 * 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||head.next==null){
            //                    ,       
            return head;
        }

        ListNode pre=head;
        ListNode p=pre.next;
        pre.next=null;
        ListNode nxt=null;

        while(p!=null){
            nxt=p.next;
            p.next=pre;
            pre=p;
            p=nxt;
        }

        return pre;

    }
}

解2(優解)
     public ListNode reverseList(ListNode head) {
            if(head==null||head.next==null){
                //                    ,       
                return head;
            }


            ListNode pReversedHead=null;
            ListNode pNode=head;
            ListNode pPrev=null;
            while(pNode!=null){
                ListNode pNext=pNode.next;
                if(pNext==null)
                    pReversedHead=pNode;
                pNode.next=pPrev;

                pPrev=pNode;
                pNode=pNext;
            }

            return pReversedHead;

        }