Problem:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULLFollow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Analysis:
本题逆转链表采用的就是头插法。代码如下:
Code:
/**
* 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)
return head;
ListNode res = new ListNode(-1);
ListNode p = head;
while(p != null) {
ListNode temp = new ListNode(p.val);
ListNode nxt = res.next;
res.next = temp;
temp.next = nxt;
p = p.next;
}
return res.next;
}
}