Partition List

来源:互联网 发布:JavaScript this 编辑:程序博客网 时间:2024/05/20 23:02

题目86:Partition List

题目描述:
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.
题目分析:
partition,首先想起快速排序的partition分区,这个还不太一样,要求低一些,只需要将小于key和大于等于key的结点分成左右两边即可。
思路:
1. 遍历一遍,将小于key的结点建成一个链表,大于等于key的结点建成一个链表,再将两个链表连接;
2. 快慢指针:一个指针是遍历指针,一个指针指向需要插入的位置;
链表中添加头结点、头插法、两个指针的方法挺常用的。

1. 两个指针法

思路:
两个指针,一个指针mov作为遍历指针,一个指针pre指向需要插入的位置的前驱,先是找到第一个大于key的结点,确定小于key的结点的插入位置,mov指针继续找找到小于key的结点插入。

/** * 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 *mov, *pre, *hhead;        hhead = new ListNode(0);        hhead->next = head;        mov = hhead;        pre = mov;        while (mov->next) {            if (mov->next->val < x) {                /* 判断==,千万不要写错“=”号*/                if (mov->next == pre->next) {                    mov = mov->next;                    pre = mov;                    continue;                }                /* 不要让链表断掉 */                ListNode *temp = mov->next;                mov->next = temp->next;                temp->next = pre->next;                pre->next = temp;                pre = temp;            } else {                mov = mov->next;            }        }        /* 这样返回 */        head = hhead->next;        delete hhead;          return head;    }};
0 0
原创粉丝点击