美文网首页
lintcode 32 翻转链表

lintcode 32 翻转链表

作者: jose_dl | 来源:发表于2017-08-11 12:48 被阅读0次

    翻转一个链表

    • 样例:
      给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
    思路:必须要有三个节点。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;
        }
    }
    

    相关文章

      网友评论

          本文标题:lintcode 32 翻转链表

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