leetcode笔记:Partition List

来源:互联网 发布:安卓新闻推荐 知乎 编辑:程序博客网 时间:2024/06/11 15:57

一. 题目描述

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

二. 题目分析

题目的大意是,给定一个单链表和一个值x,把链表中小于x的放到x的前面,大于等于x的放到x的后面,每部分元素的原始相对位置不变。

该题是一个普通的链表遍历的题目,需要注意的地方在于必须将链表的最后一个节点的下一个节点更新为null,不然链表会出现环,从而导致死循环的情况。

三. 示例代码

#include <iostream>struct ListNode{    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};class Solution{public:    ListNode *partition(ListNode *head, int x)    {        ListNode *LessHeader = new ListNode(10);        ListNode *LessTail = LessHeader;        ListNode *GreaterHeader = new ListNode(10);        ListNode *GreaterTail = GreaterHeader;        while(head != NULL)        {            if (head->val < x)            {                LessTail->next = head;                LessTail = head;            }            else            {                GreaterTail->next = head;                GreaterTail = head;            }            head = head->next;        }        LessTail->next = GreaterHeader->next;        GreaterTail->next = NULL;        delete GreaterHeader;        head = LessHeader->next;        delete LessHeader;        return head;    }};

四. 小结

3 0