题目简介
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
自己的解法
// 递归做法
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null)
return head;
ListNode p=head;
if(p.next==null){
return p;
}
else{
ListNode t=reverseList(p.next);
p.next.next=p;
p.next=null;
return t;
}
}
}
Hot解法
//迭代解法
public ListNode reverseList(ListNode head) {
/* iterative solution */
ListNode newHead = null;
while (head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
//递归算法
public ListNode reverseList(ListNode head) {
/* recursive solution */
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);
}