数据结构与算法实验课 - 链表

数据结构与算法实验课 - 链表

Oct 22, 2013
C/C++

ListA()创建一个链表并插入一个元素,ListB()创建一个链表并删除两个数之间的元素。

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define NULL 0
void listA(){
	static int n;
	int *p,i,k,x;
	printf("请输入n的长度:\n");
	scanf("%d",&n);
	p=(int *)malloc(n*sizeof(int));
	printf("请输入链表的长度:\n");
	for (i=0;i<n;i++){
		scanf("%d",&p[i]);
	}
	for (i=0;i<n;i++){
		printf("%d ",p[i]);
	}
	printf("\n");


	printf("请输入要插入的序号和元素k,x:\n");
	scanf("%d,%d",&k,&x);
	if (k<1||k>n){
		printf("wrong\n");
		return;
	}
	p=(int *)realloc(p,(n+1)*sizeof(int));
	for (i=n+1;i>=k;i--){
		p[i]=p[i-1];
	}
	for (i=1;i<n+1;i++){
		if (i==k){
			p[i-1]=x;
		}
	}
	printf("the list is:\n");
	for (i=0;i<n+1;i++){
		printf("%d ",p[i]);
	}
	printf("\n");
}

struct node{
	int num;
	struct node *next;
};

void listB(){
	struct node *p,*head,*q;
	int n,i;
	int min,max;
	printf("please input 链表的个数:");
	scanf("%d",&n);
	head=(struct node *)malloc(sizeof(int));
	p=head;
	printf("\nplease input the num:\n");
	for (i=0;i<n;i++){		
		p->next=(struct node *)malloc(sizeof(int));
		scanf("%d",&p->num);
		p=p->next;	
	}
	p->next=NULL;
	p=head;
	while(p->next){
		printf("%d ",p->num);
		p=p->next;
	}
	//delete
	p=head;
	printf("\ninput min and max :");
	scanf("%d,%d",&min,&max);
	while(p->next&&p->next->num<=min){
		p=p->next;
	}
	while(p->next&&p->next->num<max){
		//q=p->next;
		p->next=p->next->next;
		//free(q);
	}
	p=head;
	printf("链表为:\n");
	while(p->next){
		printf("%d ",p->num);
		p=p->next;
	}

}
void main(){
	void listA();
	void listB();
	listA();
	listB();
}
本文共 311 字,上次修改于 Jun 19, 2022,以 CC 署名-非商业性使用-禁止演绎 4.0 国际 协议进行许可。

相关文章

» 入门结构体链表