题目206. Reverse Linked List
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
1,递归
public ListNode reverseList(ListNode head) {
ListNode tempHead = new ListNode(1);
ListNode node = head;
reverse(tempHead,node);
return tempHead.next;
}
private void reverse(ListNode head, ListNode node){
if(node == null){
return;
}
ListNode tempNode = node.next;
node.next = head.next;
head.next = node;
reverse(head,tempNode);
}
2,非递归
public ListNode reverseList(ListNode head) {
ListNode tempHead = new ListNode(1);
ListNode node = head;
ListNode tempNode = null;
while(node != null){
tempNode = node.next;
node.next = tempHead.next;
tempHead.next = node;
node = tempNode;
}
return tempHead.next;
}