现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
我建立的链表是带头结点的链表,方法是结点的换位和链表重连 我知道还有另一种新建链表两个连接的方法 ,但是不太清楚两个方法那个会好一些 时间复杂度 还是 空间复杂度哪个会好一些? 语言 python3 def divsion(self,h,data): std = h h = h.next while h.data < data and h.next: std = std.next h = h.next std_x = h h = h.next while h: if h.data <= data: h = h.next std_x.next.next = std.next std.next = std_x.next std_x.next = h std = std.next else: std_x = std_x.next h = h.next
设置两个链表一个放小于x的,一个放大于x的,最后组合到一起。python实现
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Partition: def partition(self, pHead, x): shead = ListNode(0) bhead = ListNode(0) newNode1 = shead newNode2 = bhead while pHead: if pHead.val<x: shead.next = pHead shead = shead.next else: bhead.next = pHead bhead = bhead.next pHead = pHead.next shead.next = newNode2.next bhead.next = None return newNode1.next
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Partition:
def partition(self, pHead, x):
# write code here
if pHead == None:
return None
h = ListNode(None)
h1 = ListNode(pHead.val)
pHead = pHead.next
h.next = h1
if h1.val < x:
front = h1
else:
front = h
last = h1
while pHead != None:
tem = ListNode(pHead.val)
if pHead.val >= x:
last.next = tem
last = tem
elif pHead.val < x:
tem.next = front.next
front.next = tem
front = tem
pHead = pHead.next
return h.next
class Partition:
def partition(self, pHead, x):
part1,part2=[],[]
while pHead:
if pHead.val<x:
part1.append(pHead.val)
else:
part2.append(pHead.val)
pHead=pHead.next
dummy=ListNode(0)
pre=dummy
for i in part1+part2:
node=ListNode(i)
pre.next=node
pre=pre.next
return dummy.next
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Partition: def partition(self, pHead, x): if not pHead: return None dummybefore = before = ListNode(0) dummyafter = after = ListNode(0) while pHead: if pHead.val < x: before.next = pHead before = before.next else: after.next = pHead after = after.next pHead = pHead.next after.next = None before.next = dummyafter.next return dummybefore.next