题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
using System;
using System.Collections.Generic;
/*
public class ListNode
{
public int val;
public ListNode next;
public ListNode (int x)
{
val = x;
}
}
*/
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
public bool isPail(ListNode head) {
// write code here
if (head == null || head.next == null) return true;
Stack<int> stack = new Stack<int>();
List<int> list = new List<int>();
ListNode t = head;
while (t != null) {
stack.Push(t.val);
list.Add(t.val);
t = t.next;
}
//存放反过来的链表数
List<int> re = new List<int>();
while (stack.Count != 0) {
re.Add(stack.Pop());
}
for (int i = 0; i < re.Count; i++) {
if (re[i] != list[i]) {
return false;
}
}
return true;
}
}
