Reverse a singly linked list.
我的代码
如果拉掉注释那一句,那么链表末尾会形成一个圈,超时
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode before, now, after;
before = head;
if(head == null || head.next == null){
return head;
}
now = head.next;
head.next = null; //一开始落了这一句
if(now.next == null){
now.next = before;
before.next = null;
return now;
}
after = now.next;
while(after != null){
now.next = before;
before = now;
now = after;
after = after.next;
}
now.next = before;
return now;
}
}
discuss中解法
public ListNode reverseList(ListNode head) {
/* iterative solution */
ListNode newHead = null;
while (head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
public ListNode reverseList(ListNode head) {
/* recursive solution */
return reverseListInt(head, null);
}
private ListNode reverseListInt(ListNode head, ListNode newHead) {
if (head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseListInt(next, head);
}