optimal solution
public ListNode Reverse(ListNode head){
var node = head;
ListNode prev = null;
while(node != null){
var next = node.next;
node.next = prev;
prev = node;
node = next;
}
return prev;
}
not optimal solution
public ListNode ReverseList(ListNode head) {
if (head == null)
return null;
ListNode current = head;
var links = new List<ListNode>();
ListNode lastNode = null;
while (current != null){
if (current.next != null)
links.Add(current);
if (current.next == null)
lastNode = current;
current = current.next;
}
var reversedHead = lastNode;
Console.WriteLine("lastNodeValue=" + lastNode.val);
current = lastNode;
for (var i = links.Count() - 1; i >= 0; i -- ){
current.next = links[i];
current = current.next;
}
current.next = null;
return reversedHead;
}