Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution:
非递归和递归实现。
非递归版本:定义三个指针,pre,cur,next。从前向后修改指针。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null ||head.next == null) {
return head;
}
ListNode cur = head;
ListNode pre = null;
ListNode next = null;
ListNode newhead = null;
while(cur != null) {
next = cur.next;
if(next == null) { //说明到达最后
newhead = cur;
cur.next = pre; //最后一个也要连上前面
break;
}
cur.next = pre;
pre = cur;
cur = next;
}
return newhead;
}
}
递归版本:和迭代版本思路类似,只不过这个是从后向前修改。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null ||head.next == null) {
return head;
}
ListNode newhead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newhead;
}
}