LeetCode#86 Partition List (week4)

来源:互联网 发布:2017程序员笔记本推荐 编辑:程序博客网 时间:2024/06/07 06:21

week4(problem2)

题目

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.
原题地址:https://leetcode.com/problems/partition-list/description/

解析

题目给定一个链表,链表节点定义如下

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */

将所有比给定x小的节点移动到所有大于等于x的节点的前面。
大致思路为用两个队列存放需要移动和不需要移动的节点的数值,构造新的链表时先存放所有需要移动的节点再存放不需移动的节点,得到的新链表即为答案。

易错点解析

while (!Move.empty()) {            temp2 = new ListNode(Move.front());            Move.pop();            if (isHead) {                result = temp2;                isHead = false;            }            temp2 = temp2->next;        }

如上代码,在两次以上的循环中,temp2所new的节点并不是上一个节点的next,最终得到的节点并没有连接起来,这大概是像作者这种菜鸟所犯的常见错误,正确的做法如下面所示的代码。

代码

class Solution {public:    ListNode* partition(ListNode* head, int x) {        if (head == NULL) {            return NULL;        }        queue<int> Original;        queue<int> Move;        ListNode* temp = head;        while (temp != NULL) {            if (temp->val < x) {                Move.push(temp->val);            }            else {                Original.push(temp->val);            }            temp = temp->next;        }        ListNode *temp2;        ListNode *result;        /*记录当前构造的节点是否为头节点*/        bool isHead = true;        while (!Move.empty()) {            if (isHead) {                temp2 = new ListNode(Move.front());                Move.pop();                result = temp2;                isHead = false;            }            else {                temp2->next = new ListNode(Move.front());                Move.pop();                temp2 = temp2->next;            }        }        while (!Original.empty()) {            if (isHead) {                temp2 = new ListNode(Original.front());                Original.pop();                result = temp2;                isHead = false;            }            else {                temp2->next = new ListNode(Original.front());                Original.pop();                temp2 = temp2->next;            }        }        return result;    }};
原创粉丝点击