标签:
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; } }
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4514899.html