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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[Leetcode][JAVA] Reorder List

發(fā)布時間:2025/3/13 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Leetcode][JAVA] Reorder List 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Given a singly linked list?L:?L0→L1→…→Ln-1→Ln,
reorder it to:?L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given?{1,2,3,4}, reorder it to?{1,4,2,3}.

?

比較容易思考且實現(xiàn)的一個思路是, 將鏈表從中心拆成兩半,后一半全部反向連接,然后前一半和后一半一個一個節(jié)點交替連接。

拆分階段使用快慢指針方法即可得到兩個平分的鏈表。

反向和合并階段就是很常規(guī)的鏈表操作。

代碼:

1 public void reorderList(ListNode head) { 2 if(head==null || head.next==null) 3 return; 4 //split 5 ListNode fast = head; 6 ListNode slow = head; 7 while(true) 8 { 9 fast = fast.next.next; 10 if(fast==null || fast.next==null) 11 break; 12 slow = slow.next; 13 } 14 fast = slow.next; 15 slow.next = null; 16 slow = head; 17 //reverse fast 18 fast = reverse(fast); 19 //insert 20 while(slow!=null && fast!=null) 21 { 22 ListNode snext=slow.next; 23 ListNode fnext=fast.next; 24 slow.next=fast; 25 if(snext!=null) 26 fast.next=snext; 27 slow = snext; 28 fast = fnext; 29 } 30 } 31 public ListNode reverse(ListNode head) 32 { 33 ListNode cur = head; 34 ListNode pre = null; 35 while(cur!=null) 36 { 37 ListNode temp = cur.next; 38 cur.next = pre; 39 pre = cur; 40 cur = temp; 41 } 42 return pre; 43 }

?

轉(zhuǎn)載于:https://www.cnblogs.com/splash/p/4009994.html

總結(jié)

以上是生活随笔為你收集整理的[Leetcode][JAVA] Reorder List的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。