lintcode 32 翻转链表

2017-08-11  本文已影响0人  jose_dl

翻转一个链表

思路:必须要有三个节点。cur,一个保存下一次要访问的节点,before,一个是这一次断开的哪个节点,last是断开的这个点before要连接到的那个点。

public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode cur=head;
        ListNode last=null;
        ListNode before=null;
        while(cur!=null){
            last=before;
            before=cur;
            cur=cur.next;
            before.next=last;
        }
       return before;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读