leetcode86 分隔链表

由于学习数据结构的时候老师使用的java语言,所以,一方面为了加深对各种数据结构的运用和理解,也为了熟悉数据结构在c语言中的应用,决定从链表开始,每种数据结构,都要至少找到十个题进行练习,对自己比较有启发的题目就单独拿出来,否则就放在杂记中。

题目大意
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
eg:输入1 4 3 2 5 2 3
输出1 2 2 4 3 5

解答

#include <iostream>
#include <cstdlib>
using namespace std;


struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}//值得借鉴的构造函数 
};

ListNode* partition(ListNode* head, int x)//以下的算法都未涉及结点,都是指向结点的指针 
{
	ListNode *ans=new ListNode(-1);//初始化为-1是为了将头结点与其余的结点区分开 
	ListNode *pointer=new ListNode(-1);
	ListNode *first=ans;//需要移动 
	ListNode *second=pointer;//需要移动 
	while(head)
	{
		if(head->val<x)
		{
			
			first->next=head;
			first=first->next;
//			first->next=NULL;//这句话是不需要的,会让执行结果变成只有1 
			
		}
		else
		{
			second->next=head;
			second=second->next;
//			second->next=NULL;//这句话是不需要的,我们只要保证最后返回的链表的末尾为NULL即可 
			
		}
		head=head->next;
	}
	first->next=pointer->next;
	second->next=NULL;//这句话极其关键,目的是将返回的链表的末尾置空,使其不会乱指 
	return ans->next; 
}

int main()
{
	ListNode* temp2=new ListNode(1);
	ListNode* temp3=new ListNode(4);
	ListNode* temp4=new ListNode(3);
	ListNode* temp5=new ListNode(2);
	ListNode* temp6=new ListNode(5);
	ListNode* temp7=new ListNode(2);
	temp2->next=temp3;
	temp3->next=temp4;
	temp4->next=temp5;
	temp5->next=temp6;
	temp6->next=temp7;
	temp7->next=NULL;
	ListNode* temp=partition(temp2,3);
	while(temp)
	{
		cout<<temp->val<<endl;
		temp=temp->next;
	}
	cout<<"ok"<<endl;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值