当前位置: 首页 > 后端技术 > Java

LeetCode-234-PalindromeLinkedList

时间:2023-04-01 22:58:19 Java

PalindromeLinkedList题目描述:请判断一个链表是否为回文链表。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:链表遍历首先,如果头部为空或者只有一个节点,直接返回true。当head大于1个节点时,先遍历链表,用count记录链表节点的个数作为count,然后将链表的第一个count/2入栈,然后将后半部分放入比较链表中的节点和栈中的节点元素,不同则返回false。如果都一样,最后返回true。importjava.util.Stack;publicclassLeetCode_234{publicstaticbooleanisPalindrome(ListNodehead){if(head==null||head.next==null){returntrue;}ListNodecur=head;//链表节点数intcount=0;while(cur!=null){count++;cur=cur.next;}//将前半部分节点入栈Stacktemp=newStack<>();ListNodenewCur=head;对于(inti=1;i<=count/2;i++){temp.push(newCur.val);newCur=newCur.next;}开始;if(count%2==0){开始=count/2+1;}else{开始=计数/2+2;newCur=newCur.next;}for(inti=start;i<=count;i++){if(temp.pop()!=newCur.val){returnfalse;}newCur=newCur.next;}返回真;}公众号taticvoidmain(String[]args){ListNodehead=newListNode(1);head.next=newListNode(0);head.next.next=newListNode(1);System.out.println(isPalindrome(head));}}【每日留言】为别人鼓掌的人,也在为自己的生活喝彩