判断一个链表是否为回文结构
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
数据范围: 链表节点数 0≤n≤105,链表中每个节点的值满足 ∣val∣≤107
示例1
输入:
{1}
返回值:
true
示例2
输入:
{2,1}
返回值:
false
说明:
2->1
示例3
输入:
{1,2,2,1}
返回值:
true
说明:
1->2->2->1
解法1:转换为数组
- 首先初始化一个list列表;
- 遍历链表,将链表中的值转移至list中;
- 在list中通过比较头尾的值来判断链表是否为回文结构
public bool isPail (ListNode head) {
// write code here
//只有一个结点一定是回文结构
if(head.next == null) return true;
List<int> list = new List<int>();
while(head != null)
{
list.Add(head.val);
head = head.next;
}
int left = 0,right = list.Count - 1;
while(left < right)
{
if(list[left] != list[right]) return false;
left++;
right--;
}
return true;
}
解法2:反转后半部分链表
public bool isPail (ListNode head) {
// write code here
//只有一个结点一定是回文结构
if(head.next == null) return true;
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null)
{
fast = fast.next.next;
slow = slow.next;
}
// 如果fast 为空,则链表长度为偶数个,否则链表长度为奇数个
if(fast != null)
{
slow = slow.next;
}
//反转后半部分链表
slow = ReversListNode(slow);
fast = head;
while(slow != null)
{
//开始比较
if(slow.val != fast.val) return false;
slow = slow.next;
fast = fast.next;
}
return true;
}
public ListNode ReversListNode(ListNode node)
{
ListNode head = null;
while(node != null)
{
ListNode temp = node.next;
node.next = head;
head = node;
node = temp;
}
return head;
}