leetcode 86 分隔链表 / partition list

题目描述:


    又是关于链表的操作题,感觉自己做这类题比较缺乏经验,想到哪写到哪,代码原没有别人简洁明了,还需要多多学习。

参考代码:

/**
 * 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 dummy1(-1),dummy2(-1);
        ListNode *root1=&dummy1,*root2=&dummy2;
        while(head){
            if(head->val<x){
                root1->next=head;
                head=head->next;
                root1=root1->next;
                root1->next=NULL;
            }
            else{
                root2->next=head;
                head=head->next;
                root2=root2->next;
                root2->next=NULL;
            }
        }
        root1->next=dummy2.next;
        return dummy1.next;
    }
};

我的:

/**
 * 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* q = head;
		ListNode* temp;
		int total = 1;
		while(q -> next != NULL){
			total += 1;
			q = q -> next;
		} // q记录最后一个节点
		ListNode* p = head;
		int cnt = 0;
		while(p -> val >= x && cnt < total){ // 找到第一个小于x的节点
			temp = p;
			q -> next = temp;
			p = p -> next;
			temp -> next = NULL;
			q = temp;
			cnt += 1;
		}
		if(cnt > total) return p;
		cnt += 1;
		if(cnt == total) return p;
		ListNode* begin = p;
		while(cnt < total){
			if(p -> next != NULL && p -> next -> val < x){
				p = p -> next;
				cnt += 1;
			}
			else if(p -> next != NULL && p -> next -> val >= x){
				temp = p -> next;
				q -> next = temp;
				p -> next = p -> next -> next;
				temp -> next = NULL;
				q = temp;
				cnt += 1;
			}
		}
		return begin;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值