码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Linked List

时间:2015-05-19 18:25:09      阅读:76      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!