Reverse a singly linked list.
Java
/**
* 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 prev = head;
ListNode current = head.next;
ListNode nex = current.next;
while(current.next != null)
{
current.next = prev;
prev = current;
current = nex;
nex = nex.next;
}
current.next = prev;
return current;
}
}
这个会无法通过:
Memory Limit Exceeded
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode prev = null;
while(head != null)
{
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}