您的位置:首页 > 其它

Reverse a LinkedList 链表倒置

2015-06-16 17:05 302 查看

两种方法倒置一个链表

1. 递归

亮点在于构建一个假的head:newHead,代码如下:

class RecursivelyReverseLinkedList{
ListNode newHead = new ListNode(0);
public ListNode reverseList(ListNode head) {
if(head == null) {
return null;
} // empty list
reverseList(newHead, head); // recursion
return newHead.next;
}

public ListNode reverseList(ListNode head, ListNode p) {
head.next = p; // connect the head and the list
if(p.next != null) {
ListNode p1 = new ListNode(0); // new head
ListNode q = reverseList(p1, p.next); // get the last non empty node
p.next = null; // to put the p in new list
q.next = p; // connect
head.next = p1.next; // connect
}
return p; // return the last non empty node
}
}


2. 迭代

public ListNode reverseList(ListNode head) {
if(head == null) {
return null;
} // return empty list
ListNode newHead = new ListNode(0); // new head
ListNode p = head; // temp index
while(p != null) {
ListNode temp = p; // get off the first node
p = p.next; // move to next node
temp.next = newHead.next; // connect
newHead.next = temp;
}
return newHead.next; // return the right head
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: