Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
LeetCode206 reverse a singly linked list
Example:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
Advanced:
You can reverse the iterative or recursively list. Can you solve this question in two ways?
Iteration:
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
ListNode tmp = null;
while(cur!=null){
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
Recursion:
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode nextNode = head.next;
ListNode p = reverseList(nextNode);
nextNode.next = head;
head.next = null;
return p;
}