由于学习数据结构的时候老师使用的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;
}