给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
输入:head = [1,2,2,1]
输出:true
输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/palindrome-linked-list
//1
public class Solution
{
public bool IsPalindrome(ListNode head)
{
IList<int> nums = new List<int>();
ListNode node = head;
while (node != null)
{
nums.Add(node.val);
node = node.next;
}
int size = nums.Count;
for (int i = (size - 1) / 2; i >= 0; i--)
{
int j = size - 1 - i;
if (nums[i] != nums[j])
{
return false;
}
}
return true;
}
}
//2
public class Solution
{
public bool IsPalindrome(ListNode head)
{
ListNode fast = head, slow = head;
while (fast != null && fast.next != null)
{
fast = fast.next.next;
slow = slow.next;
}
bool odd = fast != null;
ListNode firstHalfEnd = slow;
ListNode secondHalfStart = odd ? slow.next : slow;
ListNode node1 = ReverseFirstHalf(head, firstHalfEnd);
ListNode node2 = secondHalfStart;
while (node1 != null)
{
if (node1.val != node2.val)
{
return false;
}
node1 = node1.next;
node2 = node2.next;
}
return true;
}
public ListNode ReverseFirstHalf(ListNode head, ListNode firstHalfEnd)
{
ListNode prev = null, curr = head;
while (curr != firstHalfEnd)
{
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}