【Leetcode】Reverse LinkedList

太經典的題目了,我就不廢話了,只是爲了po這個我非常obsessed的方法:

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


public ListNode reverseList(ListNode head) {
    if(head==null || head.next == null) 
        return head;
 
    ListNode p1 = head;
    ListNode p2 = head.next;
 
    head.next = null;
    while(p1!= null && p2!= null){
        ListNode t = p2.next;
        p2.next = p1;
        p1 = p2;
        if (t!=null){
            p2 = t;
        }else{
            break;
        }
    }
 
    return p2;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章