leetcode 234. 回文链表(快慢指针+链表倒置)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 234. 回文链表(快慢指针+链表倒置)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
請判斷一個鏈表是否為回文鏈表。
示例 1:
輸入: 1->2
輸出: false
示例 2:
輸入: 1->2->2->1
輸出: true
代碼
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/ class Solution {public boolean isPalindrome(ListNode head) {if(head==null||head.next==null) return true;ListNode fast=head,slow=head,pre=null;while (fast!=null&&fast.next!=null){pre=slow;slow=slow.next;fast=fast.next.next;}//快慢指針找出中點pre.next=null;//從中點切斷鏈表pre=null;while (slow!=null)//倒置后部分鏈表{ListNode temp=slow.next;slow.next=pre;pre=slow;slow=temp;}while (pre!=null&&head!=null)//將兩個鏈表比較{if(pre.val!=head.val) return false;pre=pre.next;head=head.next;}return true;} }總結
以上是生活随笔為你收集整理的leetcode 234. 回文链表(快慢指针+链表倒置)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到竹叶青蛇预示着什么
- 下一篇: 梦到两头大象是什么意思周公解梦