Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
反转链表
模板了
public ListNode reverseList(ListNode head)
{
if(head==null)
return head;
ListNode prev=head;
ListNode p=head.next;
ListNode pnext=null;
while(p!=null)
{
pnext=p.next;
p.next=prev;
prev=p;
p=pnext;
}
head.next=null;
return prev;
}
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null)
return head;
ListNode nextNode=head.next;
ListNode newHead=reverseList(nextNode);
nextNode.next=head;
head.next=null;
return newHead;
}