leetcode【第八周】链表划分

来源:互联网 发布:网络虚拟手机号发短信 编辑:程序博客网 时间:2024/06/09 16:11

问题描述:

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.

问题分析:

不难想到,构建两个链表,顺序读取原链表,值小于阙值的节点和大于等于阙值的节点分别按顺序放到两个新链表中,最后再将小于阙值的链表尾指向大于等于阙值的链表头。值得注意的是,最后要把大于等于阙值的链表最后一个节点的指针指向空,以防循环。

代码如下:

/** * 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) {        if(head==NULL)            return NULL;        ListNode* litterHead = new ListNode(0);        ListNode* litter = litterHead;        ListNode* greaterHead = new ListNode(0);        ListNode* greater = greaterHead;        ListNode* curr = head;        while(curr)        {            if(curr->valnext = curr;                litter = litter->next;                curr = curr->next;            }else            {                greater->next = curr;                greater = greater->next;                curr = curr->next;            }        }        greater->next = NULL;        litter->next = greaterHead->next;        return litterHead->next;                }};

0 0
原创粉丝点击