11.链表分割
问题:
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
解决:
思想:
用一个small存储比x小的结点,用big存储比x大的结点。然后将二者拼接
python代码:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Partition:
def partition(self, pHead, x):
# write code here
smallnode=ListNode(0)
bignode=ListNode(0)
small=smallnode
big=bignode
while pHead is not None:
if pHead.val<x:
small.next=pHead
small=small.next
else:
big.next=pHead
big=big.next
pHead=pHead.next
big.next=None
small.next=bignode.next
return smallnode.next