日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode 234题回文链表

發布時間:2024/3/26 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode 234题回文链表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.


回文就是正著念,反著念是一樣的,給出了3種解
首先正著最先得數得在右半部分會最后一個,滿足棧的先進后出特性所以可以用一個棧來解決這個問題

用N個空間

這太簡單了不說了

public static boolean isPalindromeList1(ListNode head){if(head==null||head.next==null){return true;}Stack<Integer> stack = new Stack<>();ListNode p = head;while(p!=null){stack.push(p.val);p=p.next;}p = head;while(!stack.isEmpty()){if(stack.pop()!=p.val){return false;}p=p.next;}return true;}

用一半的空間

可以從鏈表的中點開始,把后半部分壓入棧中,然后跟鏈表的前半部分對比全相同就滿足回文
快慢指針法尋找中點,注意循環判斷的條件是棧為空,比判斷鏈表中點的位置要簡單。。有時候可以換個思路

public static boolean isPalindromeList2(ListNode head){if(head==null||head.next==null){return true;}Stack<Integer> stack = new Stack<>();ListNode fast = head.next;ListNode slow = head;while(fast!=null&&fast.next!=null){slow = slow.next;fast = fast.next.next;}while(slow!=null){stack.push(slow.val);slow = slow.next;}//從鏈表的后半段判斷是否為回文結構while(!stack.isEmpty()){//判斷棧為空if(head.val!=stack.pop()){return false;}head = head.next;}return true;}

O(1)空間復雜度

思路簡單,把鏈表后半部分逆序然后兩個指針往中間走就行
難在邊界的判斷上

定義三個指針 tail保存已經逆好序的倆表,cur指向要逆序的結點,old保存下一個結點。循環條件為cur!=null cur指向tail 然后tail=cur 然后 cur = old


根據奇偶長度不同,判斷條件為兩個端點誰指向空就結束(判斷回文)
最后別忘了把順序恢復到正常

public static boolean isPalindromeList3(ListNode head ){if(head==null||head.next==null){return true;}ListNode fast = head.next;ListNode slow = head;while(fast!=null&&fast.next!=null){slow = slow.next;fast = fast.next.next;}//反轉鏈表ListNode tail = slow;ListNode cur = tail.next; //cur = right part frist nodeListNode old = null;slow.next = null;//mid.next = nullwhile(cur!=null){//right part convertold = cur.next; //cur.next = tail;tail = cur;cur = old;} // printList(head); // printList(tail);//復用兩個指針 cur oldcur = head;old = tail;while(cur!=null&old!=null){if(cur.val!=old.val){return false;}cur = cur.next;old = old.next;}cur = tail.next;//not null//只能從最后一個結點來逆序 因為是單向鏈表只能順著方向來tail.next = null;//last node ->nullwhile(cur!=null){old = cur.next;cur.next = tail;tail = cur;cur = old;} // printList(head);return true;}

總結

以上是生活随笔為你收集整理的leetcode 234题回文链表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。