首页 > 其他 > 详细

Reverse Linked List

时间:2015-05-19 18:24:29      阅读:132      评论:0      收藏:0      [点我收藏+]

https://leetcode.com/problems/reverse-linked-list/

Reverse a singly linked list.

解题思路:

类似于插入排序,始终将当前节点插入到最前方。

/**
 * 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 dummy = new ListNode(0);
        dummy.next = head;
        ListNode first = head;
        ListNode last = head;
        while(last.next != null) {
            ListNode next = last.next.next;
            dummy.next = last.next;
            dummy.next.next = first;
            last.next = next;
            first = dummy.next;
        }
        return dummy.next;
    }
}

但是这样很复杂有没有感觉到?straight forward的方法是,维护两个指针,不断向后面一个的next指向前面的就完成倒置了。

/**
 * 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 cur = head.next;
        head.next = null;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

 

Reverse Linked List

原文:http://www.cnblogs.com/NickyYe/p/4514899.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!