leetcode 86: Delimited linked lists

Topic: Delimited linked list


  • Topic description:
    Given a linked list and a specific value x, partition the linked list such that all nodes less than x come before nodes greater than or equal to x.
    You should keep the initial relative position of each node in both partitions.
  • Example

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

/**
 * 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 less_head(0);   //设置两个临时的头节点
        ListNode more_head(0);
        ListNode *less_ptr = &less_head;   //对应指针指向两个头节点
        ListNode *more_ptr = &more_head;
        while(head){
            if(head->val < x){  //如果节点值小于x,则将节点插入less_ptr后
                less_ptr->next = head;
                less_ptr = head;
            }
            else{  //否则将节点插入more_ptr后
                more_ptr->next = head;
                more_ptr = head;
            }
            head = head->next;  //遍历链表
        }
        less_ptr->next = more_head.next;
        more_ptr->next = NULL;  //将more_ptr即链表尾节点next置空
        return less_head.next;  //less_head的next节点即为新链表头节点,返回
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325968370&siteId=291194637