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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

LintCode Python 简单级题目 96.链表划分

發(fā)布時(shí)間:2024/9/5 python 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LintCode Python 简单级题目 96.链表划分 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

原題描述:

?

給定一個(gè)單鏈表和數(shù)值x,劃分鏈表使得所有小于x的節(jié)點(diǎn)排在大于等于x的節(jié)點(diǎn)之前。

你應(yīng)該保留兩部分內(nèi)鏈表節(jié)點(diǎn)原有的相對(duì)順序。

?

您在真實(shí)的面試中是否遇到過這個(gè)題?? Yes

?

樣例

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

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

?

標(biāo)簽? 兩根指針?鏈表

?

題目分析:

添加兩個(gè)指針,分別指向第一個(gè)大于等于X的第一個(gè)節(jié)點(diǎn)和小于X的第一個(gè)節(jié)點(diǎn),

實(shí)際情況就是第N個(gè)節(jié)點(diǎn)大于等于X時(shí),N-1個(gè)節(jié)點(diǎn)必然就是小于X;

由于可能節(jié)點(diǎn)第一個(gè)值就大于X,此時(shí)不存在N-1個(gè)節(jié)點(diǎn),所以在原鏈表前新增一個(gè)節(jié)點(diǎn),用于初始化鏈表循環(huán)。

此時(shí)算法復(fù)雜度O(n)。

?

""" 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 is None or head.next is None: return headnode = ListNode(-999999)node.next = headhead = nodefollow = headpre = head# 找到第一個(gè)值大于x的節(jié)點(diǎn)while follow is not None and follow.val < x:pre = followfollow = follow.next# 所有節(jié)點(diǎn)都小于x,直接返回原h(huán)eadif follow is None: return head.next# 遍歷鏈表,此時(shí)pre是follow的上一個(gè)節(jié)點(diǎn)while follow.next is not None:if follow.next.val < x:# 刪除原節(jié)點(diǎn)other = follow.nextfollow.next = follow.next.next# 將其值插入到pre之后tmp = pre.nextother.next = tmppre.next = otherpre = pre.nextcontinuefollow = follow.nextreturn head.next

?

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

與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖

總結(jié)

以上是生活随笔為你收集整理的LintCode Python 简单级题目 96.链表划分的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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