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?

iterative 解法:

总结就是得到下一个节点,更改当前节点指向,将指针往下移动,直到过完整个linkedlist.

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while(cur!=null){
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}
/**
* 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;
// 1->2->3->4->null
ListNode nextNode = head.next; // 2->3->4->null
ListNode reversed = reverseList(nextNode); //4->3->2->null
nextNode.next = head; //4->3->2->1
head.next = null; //4->3->2->1->null
return reversed;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode rev = null;
ListNode temp1 = head;
while(temp1 != null) {
if (rev == null) {
rev = new ListNode(temp1.val);
} else {
ListNode tnew = new ListNode(temp1.val);
tnew.next = rev;
rev = tnew;
}
temp1 = temp1.next;
}
return rev;
}
}