您的位置:首页 > 其它

【leetcode】206.Reverse Linked List

2018-01-31 14:15 316 查看

206.Reverse Linked List

Reverse a singly linked list.

Tips:实现从尾到头打印一个链表。

以下代码包括两张方法:

①使用栈实现,不改变原链表。先读入,后输出。典型的先进后出,可用栈来实现。

②改变原来链表的指针方向。

package easy;

import java.util.Stack;
import easy.ListNode;

public class L206ReverseLinkedList {
/**
* Definition for singly-linked list.
*
* public class ListNode { int val; ListNode next; ListNode(int x) { val =
* x; } }
*/

public ListNode reverseList(ListNode head) {
if (head == null)
return head;
Stack<Integer> myStack = new Stack<Integer>();
ListNode pNode = head;
while (pNode != null) {
myStack.push(pNode.val);
pNode = pNode.next;
}
int size = myStack.size();
ListNode newHead = new ListNode(myStack.peek());
myStack.pop();
if (size == 1)
return newHead;
ListNode node = new ListNode(myStack.peek());
newHead.next = node;
myStack.pop();
while (!myStack.empty()) {
node.next = new ListNode(myStack.peek());
myStack.pop();
node = node.next;
}
return newHead;
}

public ListNode reverseList2(ListNode head) {
// 通过改变链表的指针来从尾到头打印链表。
if (head == null || head.next == null)
return head;
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}

public void print(ListNode phead) {
while (phead != null) {
System.out.println(phead.val);
phead = phead.next;
}
}

public static void main(String[] args) {
ListNode head1 = new ListNode(1);
ListNode head2 = new ListNode(2);
ListNode head3 = new ListNode(3);
ListNode head4 = new ListNode(4);
head1.next = head2;
head2.next = head3;
head3.next = head4;
head4.next = null;
L206ReverseLinkedList cc = new L206ReverseLinkedList();
System.out.println("使用栈");
ListNode p1 = cc.reverseList(head1);
cc.print(p1);
System.out.println("改变指针");
ListNode p2 = cc.reverseList2(head1);
cc.print(p2);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: