您的位置:首页 > 其它

206. Reverse Linked List

2016-06-25 21:33 288 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: