LeetCode 86. 分隔链表(C++)

题目:

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

思路:

参考博客
创建两个临时节点,之后遍历整个链表,链表每个节点的值与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) {
        if(head == NULL)
            return head;
        ListNode less_head(0);  //临时头结点
        ListNode more_head(0);
        ListNode* less_ptr = &less_head;
        ListNode* more_ptr = &more_head;
        ListNode* cur = head;
        while(cur != NULL){
            if(cur->val < x){
                less_ptr->next = cur;
                less_ptr = less_ptr->next;
            }
            else{
                more_ptr->next = cur;
                more_ptr = more_ptr->next;
            }
            cur = cur->next;
        }
        less_ptr->next = more_head.next;
        more_ptr->next = NULL;
        return less_head.next;
    }
};

猜你喜欢

转载自blog.csdn.net/my_clear_mind/article/details/81835515
今日推荐