Partition List

来源:互联网 发布:网络维护实训周报 编辑:程序博客网 时间:2024/06/11 07:51

一、问题描述

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.

二、思路

题目比较有新意,算法导论中有patition算法(非常有名,是快速排序中的核心算法),但是那个算法是基于数组的,这道题目是基于链表的,我的思路是新建两个节点,形成两个链表,将小于x的值放在第一个链表,将大于等于x的值放在第二个链表,循环结束后合并两个链表即可。

三、代码

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* partition(ListNode* head, int x) {        ListNode node1(0),node2(0);        ListNode* p1 = &node1, *p2 = &node2;        while(head){            if(head -> val < x){                p1 = p1 -> next = head;            }else{                p2 = p2 -> next = head;            }            head = head -> next;        }        p2 -> next = NULL;        p1 -> next = node2.next;        return node1.next;    }};


0 0
原创粉丝点击