欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言建立链表的操作

程序员文章站 2024-02-11 13:45:04
...

尾插法建立带头结点的单链表

C语言建立链表的操作

#include<stdio.h>
#include<stdlib.h>
typedef struct Linklist{
	int data;
	struct Linklist *next;
}Node;
Node *Creat(){
	Node *Head;
	Node *pNew,*r;
	int x;
	Head = (Node*)malloc(sizeof(Node));
	Head->next = NULL;
	r = Head;
	scanf("%d",&x);
	while (x != -1){
		pNew =(Node*)malloc(sizeof(Node));
		pNew->data = x;
		r->next = pNew;//关键代码 
		r = pNew;
		scanf("%d",&x); 
	} 
	r->next = NULL;
	return Head; 
}
void Output(Node *Head){
	Node *p;
	p = Head->next;
	while (p){
		printf("%d\n",p->data);
		p = p->next;
	} 
} 
int main(void){
	Node *Head;
	printf("开始建立单链表L,输入-1结束: \n");
	Head = Creat();
	Output(Head);
	return 0; 
}

头插法建立带头结点的单链表

C语言建立链表的操作

#include<stdio.h>
#include<stdlib.h>
typedef struct Linklist{
	int data;
	struct Linklist *next;
}Node;
Node *Creat(){
	Node *Head;
	Node *pNew;
	int x;
	Head = (Node*)malloc(sizeof(Node));
	Head->next = NULL;
	scanf("%d",&x);
	while(x != -1){
		pNew = (Node*)malloc(sizeof(Node));
		pNew->data = x;
		pNew->next = Head->next;
		Head->next = pNew;
		scanf("%d",&x); 
	}
	return Head;
}
void Output (Node *Head){
	Node *p;
	p = Head->next;
	while(p){
		printf("%d\n",p->data);
		p = p->next; 
	}	 
}
int  main(void){
	Node *Head;
	printf("开始建立单链表L,输入-1结束: \n");
	Head = Creat();
	Output(Head);
	return 0;
}

相关标签: 链表的建立