您的位置:首页 > 其它

LeetCode_206 Reverse Linked List

2015-08-03 11:34 141 查看
Reverse a singly linked list.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

pre始终是首元结点的值,每次对pnext重新赋值

递归

public ListNode reverseList(ListNode head) {
if(head == null ) return null;
if(head.next == null) return head;
ListNode p = head.next;
ListNode q = reverseList(p);

head.next = null;
p.next = head;
return  q;
}


非递归

public ListNode reverseList1(ListNode head) {
if(head == null ) return null;
if(head.next == null) return head;

ListNode pre = head;
ListNode p = head.next;

head.next = null;
ListNode tmp ;
while(p!=null){
tmp = p.next;
p.next = pre;
pre = p;
p = tmp;
}
return pre;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: