Leetcode 234. 回文链表
234. 回文链表 - 力扣(LeetCode) (leetcode-cn.com)
思路 1 用栈:
1.先将head从头到尾都压入栈。
2.依次从栈中取出节点,和head及其后续节点进行比较。
3.如果从前向后第x节点和从后向前第x节点的值不相同,则这个链表不是回文链表。
func isPalindrome(head *ListNode) bool { stack := make([]*ListNode, 0) newHead := head for head != nil { stack = append(stack, head) head = head.Next } for len(stack) != 0 { node := stack[len(stack)-1] stack = stack[:len(stack)-1] if node.Val == newHead.Val { newHead = newHead.Next } else { return false } } return true }
或者用双指针
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func isPalindrome(head *ListNode) bool { stack := make([]*ListNode, 0) for head != nil { stack = append(stack, head) head = head.Next } left:=0 right:=len(stack)-1 for left<right{ if stack[left].Val==stack[right].Val{ left++ right-- }else{ return false } } return true }
以上方式的时间复杂度为O(n) ,空间复杂度O(n),不满足进阶条件,所以我想到了思路2
思路 2 :
1. 设置快慢指针,快的一次移动两个节点,慢的一次移动一个节点。
2. 当快指针为空时,慢指针刚好在中间节点。然后将中间节点后的链表反转。
3. 分别最前和最后的节点开始向中心遍历,当出现不同时,则认为此链表不是回文链表。
4. 如果需要恢复现场,那就将之前反转过的链表再次反转回来。