Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
这是迭代的方式
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode nextNode = head.next;
head.next = null;
while(nextNode!=null)
{ //1,2,3
ListNode nextNextNode = nextNode.next;
nextNode.next = head;//2->1
head = nextNode;// 2,1,3
nextNode = nextNextNode;
}
return head;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
if (head.next == null) return head;
ListNode secondElem = head.next;
head.next = null;
ListNode reverseRest = reverseList(secondElem);
secondElem.next = head;
return reverseRest;
}
}