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.

Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

思路:从前往后。

    有一些比较好的技巧,就是新建两个头结点,作为起始端。再设立左右结尾节点。一次判断,不过别忘了,最后节点指向空,不然不能通过。


代码:

class Solution {
public:
	ListNode* partition(ListNode* head, int x) {
		if (head==NULL||head->next==NULL){
			return head;
		}

		ListNode *left=new ListNode(-1),*right=new ListNode(-1);
		ListNode *leftTail=left,*rightTail=right;

		while (head!=NULL){
			if (head->val<x){
				leftTail->next=head;
				head=head->next;
				leftTail=leftTail->next;
				leftTail->next=NULL;
			}else{
				rightTail->next=head;
				head=head->next;
				rightTail=rightTail->next;
			}
		}
		right=right->next;
		leftTail->next=right;
		rightTail->next=NULL;
		return left->next;
        //最后没有设置链表指向空,所以出错。
	}
};




posted @ 2015-09-24 15:13  JSRGFJZ6  阅读(126)  评论(0编辑  收藏  举报