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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

lintcode :Partition List 链表划分

發布時間:2025/3/19 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 lintcode :Partition List 链表划分 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目:

鏈表劃分

給定一個單鏈表和數值x,劃分鏈表使得所有小于x的節點排在大于等于x的節點之前。

你應該保留兩部分內鏈表節點原有的相對順序。

樣例

給定鏈表?1->4->3->2->5->2->null,并且 x=3

返回?1->2->2->4->3->5->null

解題:

上面返回的結果好多不對的應該是:?1->2->2->3->4->5->null

想了好久不知道怎么搞,九章看到的程序,竟然搞兩個鏈表鏈接起來。。。

Java程序:

/*** Definition for ListNode.* public class ListNode {* int val;* ListNode next;* ListNode(int val) {* this.val = val;* this.next = null;* }* }*/ public class Solution {/*** @param head: The first node of linked list.* @param x: an integer* @return: a ListNode */public ListNode partition(ListNode head, int x) {// write your code hereif(head == null) return null;ListNode leftDummy = new ListNode(0);ListNode rightDummy = new ListNode(0);ListNode left = leftDummy, right = rightDummy;while (head != null) {if (head.val < x) {left.next = head;left = head;} else {right.next = head;right = head;}head = head.next;}right.next = null;left.next = rightDummy.next;return leftDummy.next;}} View Code

總耗時:?1573?ms

Python程序:

""" Definition of ListNode class ListNode(object):def __init__(self, val, next=None):self.val = valself.next = next """ class Solution:"""@param head: The first node of linked list.@param x: an integer@return: a ListNode """def partition(self, head, x):# write your code hereif head == None:return headlefthead = ListNode(0)righthead = ListNode(0)left = leftheadright = rightheadwhile head!=None:if head.val<x:left.next = head left = left.nextelse:right.next = headright = right.nexthead = head.nextright.next = Noneleft.next = righthead.nextreturn lefthead.next View Code

總耗時:?517?ms

和Java的有點小區別但是沒有影響的。

總結

以上是生活随笔為你收集整理的lintcode :Partition List 链表划分的全部內容,希望文章能夠幫你解決所遇到的問題。

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