LeetCode Partition List 非常简单易懂的解法

来源:互联网 发布:betterzip 4 for mac 编辑:程序博客网 时间:2024/06/05 07:30

/************************************************************************
* 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值,而且此方法不改变顺序。

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; //分解成两句 p1->next=head;        else                      //p1=p1->next;            p2 = p2->next = head; //同上        head = head->next;    }    p2->next = NULL;    p1->next = node2.next;    return node1.next;}
0 0
原创粉丝点击