请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

上期的问题是:163,用栈实现队列

 1class MyQueue {
 2    Stack<Integer> input = new Stack();
 3    Stack<Integer> output = new Stack();
 4
 5    public MyQueue() {
 6
 7    }
 8
 9    public void push(int x) {
10        input.push(x);
11    }
12
13    public int pop() {
14        int pop = peek();
15        output.pop();
16        return pop;
17    }
18
19    public int peek() {
20        if (output.empty())
21            while (!input.empty())
22                output.push(input.pop());
23        return output.peek();
24    }
25
26    public boolean empty() {
27        return input.empty() && output.empty();
28    }
29}

解析:

这题也可以参照前面的160,用队列实现栈,其中input是存放数据的,output会在peek的时候把input中的元素一一压栈。这道题的实现方式也有多种,下面列出大家可以自己慢慢看。

 1class MyQueue {
 2    Stack<Integer> queue = new Stack<>();
 3
 4    public void push(int x) {
 5        Stack<Integer> temp = new Stack<>();
 6        while (!queue.empty()) {
 7            temp.push(queue.pop());
 8        }
 9        queue.push(x);
10        while (!temp.empty()) {
11            queue.push(temp.pop());
12        }
13    }
14
15    public int pop() {
16        return queue.pop();
17    }
18
19    public int peek() {
20        return queue.peek();
21    }
22
23    public boolean empty() {
24        return queue.empty();
25    }
26}
27
28public class MyQueue {
29    Stack<Integer> s = new Stack<>();
30
31    public void push(int x) {
32        pushHelper(x);
33    }
34
35    public void pushHelper(int x) {
36        if (s.size() == 0) {
37            s.push(x);
38            return;
39        }
40        int data;
41        data = s.pop();
42        pushHelper(x);
43        s.push(data);
44        return;
45    }
46
47    public int pop() {
48        return s.pop();
49    }
50
51    public int peek() {
52        return s.peek();
53    }
54
55    public boolean empty() {
56        return s.size() == 0;
57    }
58}
59public class MyQueue {
60    Stack<Integer> s1 = new Stack();
61    Stack<Integer> s2 = new Stack();
62
63    public void push(int x) {
64        while (!s2.isEmpty())
65            s1.push(s2.pop());
66        s1.push(x);
67    }
68
69    public int pop() {
70        while (!s1.isEmpty())
71            s2.push(s1.pop());
72        return s2.pop();
73    }
74
75    public int peek() {
76        while (!s1.isEmpty())
77            s2.push(s1.pop());
78
79        return s2.peek();
80    }
81
82    public boolean empty() {
83        return s1.isEmpty() && s2.isEmpty();
84    }
85}