前言
以专题的形式更新刷题贴,欢迎跟我一起学习刷题,相信我,你的坚持,绝对会有意想不到的收获。每道题会提供简单的解答,如果你有更优雅的做法,欢迎提供指点,谢谢。
【题目描述】
给定一个链表的头结点 head, 请判断该链表是否为回文结构。
例如:
1->2->1,返回 true.
1->2->2->1, 返回 true。
1->2->3,返回 false。
【要求】
如果链表的长度为 N, 时间复杂度达到 O(N)。
【难度】
普通解法:士:★☆☆☆
进阶解法:尉:★★☆☆
解答
方法1
我们可以利用栈来做辅助,把链表的结点全部入栈,在一个一个出栈与链表进行对比,例如对于链表 1->2->3->2->2,入栈后如图:
然后再逐一出栈与链表元素对比。
这种解法比较简单,时间复杂度为 O(n), 空间复杂度为 O(n)。
代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23//全部入栈
public static boolean palindromeList1(Node head){
if(head == null || head.next == null){
return true;
}
Node node = head;
//使用ArrayDeque作为栈
//Stack因为集成自Vector,所以Stack类是同步的,效率不高。
//官方一般建议这样使用ArrayDeque代替Stack
ArrayDeque stack = new ArrayDeque();
while(node != null){
stack.push(node);
node = node.next;
}
while(!stack.isEmpty()){
Node popNode = stack.pop();
if(popNode.value != head.value){
return false;
}
head = head.next;
}
return true;
}
方法二
真的需要全部入栈吗?其实我们也可以让链表的后半部分入栈就可以了,然后把栈中的元素与链表的前半部分对比,例如 1->2->3->2->2 后半部分入栈后如图:
然后逐个出栈,与链表的前半部分(1->2)对比。这样做的话空间复杂度会减少一半。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29//后半部分入栈,时间复杂度O(n)
public static boolean palindromeList2(Node head){
if(head == null || head.next == null){
return true;
}
Node fast = head;//快指针
Node slow = head;//慢指针
//slow最终指向中间结点
while(fast.next!=null && fast.next.next!=null){
slow = slow.next;
fast = fast.next.next;
}
//后半部分入栈
slow = slow.next;
ArrayDeque stack = new ArrayDeque();
while(slow!=null){
stack.push(slow);
slow = slow.next;
}
//进行判断
while(!stack.isEmpty()){
Node n = stack.pop();
if(n.value != head.value){
return false;
}
head = head.next;
}
return true;
}
方法三:空间复杂度为 O(1)。
上道题我们有作过链表的反转的,没看过的可以看一下勒:【链表】打卡2:如何优雅着反转单链表,我们可以把链表的后半部分进行反转,然后再用后半部分与前半部分进行比较就可以了。这种做法额外空间复杂度只需要 O(1), 时间复杂度为 O(n)。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34//反转后半部分链表
public static boolean palindromeList3(Node head){
if(head == null || head.next == null){
return true;
}
Node slow = head;//慢指针
Node fast = head;//快指针
//slow最终指向中间结点
while(fast.next!=null && fast.next.next!=null){
slow = slow.next;
fast = fast.next.next;
}
//反转后半部分
Node reverseNode = reverseNode(slow.next);
//比较
while(reverseNode.next != null && head.next != null){
if(reverseNode.value != head.value){
return false;
}
reverseNode = reverseNode.next;
head = head.next;
}
return true;
}
private static Node reverseNode(Node head){
if(head == null || head.next == null){
return head;
}
Node newList = reverseNode(head.next);
head.next.next = head;
head.next = null;
return newList;
}
测试代码
1
2
3
4
5
6
7
8
9
10
11
12
13public static void main(String[] args){
int[] arr = {1,2,3,3,2,1};
Node head = new Node(arr[0]);
Node node = head;
int i = 0;
while(++i
node.next = new Node(arr[i]);
node = node.next;
}
System.out.println(palindromeList1(head));
System.out.println(palindromeList2(head));
System.out.println(palindromeList3(head));
}
问题拓展
思考:如果给你的是一个环形链表,并且指定了头结点,那么该如何判断是否为回文链表呢?
(完)