...的单链表,写出在其值为x的结点之后插入m个结点的程序。
发布网友
发布时间:2023-12-26 18:48
我来回答
共3个回答
热心网友
时间:2024-03-19 14:38
#include <stdio.h>
#include <malloc.h>
typedef struct st
{
int id;
struct st *next;
struct st *tailST;
}ST;
ST *getSTS(int len);//获取一个链表,节点个数为len,返回链表首地址
ST *getST(ST *headST,int con);//获取第con个节点
void printfST(ST *headST);//打印链表
int idNUM=1000;
int main()
{
int n,con;
struct st *headST=NULL,*headST2=NULL,*findST=NULL;
printf("请输入初始链表节点数量:");
scanf("%d",&n);
headST=getSTS(n);
printf("%d个节点链表已生成。\n\n",n);
printfST(headST);
printf("请输入要在第几个节点后面插入新节点:");
scanf("%d",&con);
findST=getST(headST,con);
printf("找到的节点ID:%d。\n",findST->id);
printf("请输入要插入的节点个数:");
scanf("%d",&n);
headST2=getSTS(n);
printf("---开始插入节点--\n");
headST2->tailST->next=findST->next;
findST->next=headST2->next;
printf("---插入完成--\n");
printfST(headST);
return 0;
}
void printfST(ST *headST)//打印链表
{
while(headST->next!=NULL)
{
printf("节点编号:%d\n",headST->next->id);
headST=headST->next;
}
printf("\n");
}
ST *getST(ST *headST,int con)//获取第con个节点
{
int count=0;
while(headST->next!=NULL)
{
count++;
if(count==con)
return headST->next;
headST=headST->next;
}
return NULL;
}
ST *getSTS(int len)//获取一个链表,节点个数为len,返回链表首地址
{
ST *headST=NULL,*tailST=NULL,*newST=NULL;
headST=(ST *)malloc(sizeof(ST));
headST->next=NULL;
headST->tailST=NULL;
while(len>0)
{
newST=(ST *)malloc(sizeof(ST));;
newST->id=idNUM++;
newST->next=NULL;
newST->tailST=NULL;
if(headST->next==NULL)
headST->next= newST;
else
tailST->next= newST;
tailST=newST;
len--;
}
headST->tailST=tailST;
return headST;
}
热心网友
时间:2024-03-19 14:32
#include "stdio.h"
#include <stdlib.h>
#include "time.h"
struct node{
int data;
struct node *next;
};
struct node *createnode(void){
struct node *q;
if((q=(struct node *)malloc(sizeof(struct node)))==NULL){
printf("Application memory failure, exit...\n");
exit(0);
}
return q;
}
int main(int argc,char *argv[]){
struct node *head,*p,*q;
int i,m,x;
srand((unsigned)time(NULL));
for(x=1,head=NULL,m=rand()%20+1,i=0;i<m;i++){
if(head){
p->next=createnode();
p=p->next;
p->data=x++;
p->next=NULL;
}
else{
p=head=createnode();
head->next=NULL;
}
}
printf("Please enter x & m(int)...\n");
scanf("%d%d",&x,&m);
for(p=head->next;p;p=p->next)
if(p->data==x){
for(q=p->next,i=0;i<m;i++){
p->next=createnode();
scanf("%d",&(p=p->next)->data);
}
p->next=q;
break;
}
if(p==NULL){
printf("x(%d) is not found...\n",x);
return 0;
}
for(p=head->next;p;p=p->next)//Look at...
printf("%6d",p->data);
printf("\n");
for(p=head;p->next;p=p->next,free(head),head=p);//Delete link...
free(p);
return 0;
}
运行样例:
热心网友
时间:2024-03-19 14:33
struct LNode *insert(struct LNode *head,int x,int i) { int j=1; struct LNode *s,*q; q=head; s=(struct LNode *) malloc ( sizeof(struct LNode) ); s->data=x; if(i==1) { s->next=q; head=s; } else { while(q->next != NULL) { q=q->next; j++; } if(j==i-1) { s->next=q->next; q->next=s; } else printf("error! there is no position\n"); } return(head); }