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?
思路:
翻转链表,本来不想记录了,但是是链表系列中的“hello world”,有纪念意义,主要有两种方法,迭代和递归。 注意不要断链。
代码:
java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
// iterative
/* public ListNode reverseList(ListNode head) {
if (head == null) return head;
ListNode curr = head;
ListNode prev = null;
while (curr != null) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}*/
// recursive
public ListNode reverseList(ListNode head) {
return reverseListInt(head, null);
}
private ListNode reverseListInt(ListNode head, ListNode newHead) {
if (head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseListInt(next, head);
}
}```