2022年1月17日
总结了一个关于链表的合并的模板,可以进行排序合并,主要思路是head1和head2两个链表从第一位置开始依次比较,最后存储到head3中;
构建一个双向链表并进行删除和插入操作,按要求输出。
输入格式
输入:
第一行输入元素个数M
第二行输入M个元素
第三行输入删除位置,位置为0时不删除
第四行输入插入位置和插入元素
第五行输入输出时的起始位置
输出格式
按要求的起始位置输出链表
样例输入content_copy
8
1 2 3 4 5 6 7 8
6
6 6
5
样例输出content_copy
5 6 7 8 1 2 3 4
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
node *next;
node *front;
} node;
node *creat(int num)
{
node* head=(struct node*)malloc(sizeof(struct node));
node* p1;
node* p2=head;
int data;
for(int i=0; i<num; i++)
{
scanf("%d",&data);
p1=(struct node*)malloc(sizeof(struct node));
p1->data = data;
p1->front = p2;
p2->next = p1;
p2 = p1;
}
p2->next = NULL;
return head->next;
}
node *del(node *head,int n){
if(n==0){
return head;
}
node *p;
p = head;
for(int i=1;i<n;i++){
p = p->next;
}
p->front->next = p->next;
if(p->next){
p->next->front = p->front;
}
return head;
}
node *insert(node *head,int n,int m){
node *p,*q;
p = head;
for(int i=1;i<n;i++){
p = p->next;
}
q = (struct node*)malloc(sizeof(struct node));
q->data = m;
q->front = p->front;
q->next = p;
p->front->next = q;
p->front = q;
return head;
}
int main()
{
int n;
scanf("%d",&n);
node *head,*p;
head=creat(n);
int num1,num2,element,num3;
scanf("%d",&num1);
scanf("%d %d",&num2,&element);
scanf("%d",&num3);
head = del(head,num1);
head = insert(head,num2,element);
node *head_pre = head;
for(int i=1;i<num3;i++){
head_pre = head_pre->next;
}
while(head_pre){
printf("%d ",head_pre->data);
head_pre = head_pre->next;
}
for(int i=0;i<num3;i++){
printf("%d ",head->data);
head = head->next;
}
return 0;
}
(线性表)已知不带头结点的线性链表list,链表中结点构造为(data、link),其中data为数据域,link为指针域。请写一算法,将该链表按结点数据域的值的大小从小到大重新链接。要求链接过程中不得使用除该链表以外的任何链结点空间。
输入格式
自定义链表节点数
m=5
3 1 5 4 6
输出格式
1 3 4 5 6
样例输入content_copy
8
10 1 5 14 32 55 67 6
样例输出content_copy
1 5 6 10 14 32 55 67
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
node *next;
} node;
node *creat(int num)
{
node* head=NULL;
node* p1=head;
node* p2=NULL;
int data;
for(int i=0; i<num; i++)
{
scanf("%d",&data);
if(head==NULL)
{
head=(struct node*)malloc(sizeof(struct node));
p1=head;
head->data=data;
}
else
{
p2=(struct node*)malloc(sizeof(struct node));
p1->next=p2;
p2->data=data;
p1=p2;
p1->next=NULL;
}
}
return head;
}
node *sort(node *head){
node *p,*q;
int t;
for(p=head;p!=NULL;p=p->next){
for(q=p->next;q!=NULL;q=q->next){
if(p->data > q->data){
t = p->data;
p->data = q->data;
q->data = t;
}
}
}
return head;
}
int main()
{
int n;
scanf("%d",&n);
node *head;
head = creat(n);
head = sort(head);
while(head){
printf("%d ",head->data);
head = head->next;
}
return 0;
}
链表分为带头结点的和不带头结点的,用malloc(sizeof(struct node));可以定义链表结点的宽度及链表的大小
总结
以上是生活随笔为你收集整理的2022年1月17日的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 了解 Windows Azure 存储计
- 下一篇: String,StringBuilder