导航

LeetCode86:Partition List

Posted on 2018-02-11 12:32  老刘想当个AI工程师  阅读(104)  评论(0)    收藏  举报

建立了两个ListNode变量已经两个ListNode*指针 遍历链表 将小于x值的连入一条链 将大于x值得连入一条链 最后将这两条链相连

/**
* 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 more(0);//大于x值的链
ListNode less(0);//小于
ListNode * more_pt = &more;
ListNode * less_pt = &less;

while(head){
  

  if(head->val<x){
    less_pt ->next = head;
    less_pt = head;
    }


  if(head->val>=x){
    more_pt ->next = head;
    more_pt = head;
    }

head = head->next;
}

less_pt->next = more.next;//连链 注意 因为less_pt 是指针所以用-> more是ListNode型所以用.
more_pt->next = NULL;//将表尾置空
return less.next;

}
};