目录
题目
现有一链表的头指针 SLTNode* head,给一定值k,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
思路
新增两个头节点head1和head2,将小于x的值插入到head1中,其余插入到head2中,最后head1尾指向head2.
代码
// 将所有小于 x 的结点排在其余结点之前,且不能改变原来的数据顺序
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
typedef struct SList
{
int val;
struct SList* next;
}SLTNode;
SLTNode* createlist(int* arr, int z)
{
SLTNode* head = NULL;
SLTNode* tail = NULL;
for (int i = 0; i < z; i++)
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(struct SList));
if (newnode == NULL)
{
perror("malloc fail");
exit(-1);
}
else
{
newnode->val = *(arr + i);
newnode->next = NULL;
}
if (head == NULL)
{
head = newnode;
tail = newnode;
}
else
{
tail->next = newnode;
tail = newnode;
}
}
return head;
}
void SLTPrint(SLTNode* head)
{
SLTNode* cur = head;
while (cur)
{
printf("%d->", cur->val);
cur = cur->next;
}
printf("NULL\n");
}
SLTNode* partition(SLTNode* head, int k)
{
SLTNode* head1 = NULL;
SLTNode* head2 = NULL;
SLTNode* cur = head;
SLTNode* cur1 = NULL;
SLTNode* cur2 = NULL;
int flag1 = 0;
int flag2 = 0;
while (cur)
{
if (cur->val < k)
{
if (head1 == NULL)
{
head1 = cur1 = cur;
flag1 = 1;
}
else
{
cur1->next = cur;
cur1 = cur;
}
}
else
{
if (head2 == NULL)
{
head2 = cur2 = cur;
flag2 = 1;
}
else
{
cur2->next = cur;
cur2 = cur;
}
}
cur = cur->next;
}
if (flag1 == 1 && flag2 == 1)
{
cur2->next = NULL;
cur1->next = head2;
return head1;
}
else if (flag1 == 0)
return head2;
else if (flag2 == 0)
return head1;
else
{
return head1;
}
}
void test1()
{
// 通过数组初始化单链表
int arr[] = { 1, 4, 5, 2, 6, 3 };
int k = 7;
SLTNode* plist = createlist(arr, sizeof(arr) / sizeof(arr[0]));
SLTPrint(plist);
// 链表分割,
SLTNode* newhead = partition(plist, k);
SLTPrint(newhead);
}
int main()
{
// 链表分割
test1();
return 0;
}