example.cpp

来自「数据结构的实验编程」· C++ 代码 · 共 119 行

CPP
119
字号
#include<stdio.h>
#include<malloc.h>

typedef int elemtype;
typedef struct node
{
	elemtype data;
	struct node *next;
}linklist;

linklist *creat_list()
{
	char x;
	linklist *head,*p,*r;
	p=(linklist *)malloc (sizeof(linklist));
	head=p;
	p->next=NULL;
	r=p;
	printf("creat a new one\n");
	scanf("%c",&x);
	while(x!='#')
	{
		p=(linklist *)malloc(sizeof(linklist));
		p->data=x;
		p->next=NULL;
		r->next=p;
		scanf("%c",&x);
	}
	return(head);
}

linklist *creat_list2()
{
	char x;
	linklist *head,*p,*r;
	head=NULL;
	r=head;
	scanf("%c",&x);
	while(x!='#')
	{
		p=(linklist *)malloc(sizeof(linklist));
		p->data=x;
		if(head==NULL)
			head=p;
		else
		{
			r->next=p;
			r=p;
		}
		if(r!=NULL)
			r->next=NULL;
		scanf("%c",&x);
	}
	return(head);
}

void display_list(linklist *head)
{
	linklist *p;
	p=head->next;
	while(p!=NULL)
	{
		printf("%d",p->data);
		p=p->next;
	}
}

linklist *getelem_list(linklist *head,int i)
{
	int j;
	linklist *p;
	p=head;
	j=0;
	while((p->next!=NULL)&&(i>j))
	{
		p=p->next;
		j++;
	}
	if(!p||j>i)
	{
		printf("error\n");
		return(NULL);
	}
	else
		return p;
}

linklist *findlist(linklist *head,elemtype x)
{
	linklist *p;
	p=head->next;
	while(p->data!=x && p!=NULL)
	{
		p=p->next;
	}
	if(p!=NULL)
	{
		printf("found\n");
		return(p);
	}	
	else
	{
		printf("no found\n");
		return(NULL);
	}
}

void main(void)
{
	//creat_list();
	//display_list(creat_list());
	node *i=creat_list();
	printf("%d",i);
	int j;
	scanf("%d",&j);
	printf("%d",
		getelem_list(i,j));
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?