线性结构之链表的基本操作

内容包括链表结点的定义,初始化,创建,插入,删除,输出等。

  • 结点的创建:
typedef struct node
{
	int data;//数据域
	struct node *next;//结点域
}Node;
  • 链表的初始化:
Node* InitList()
{
	Node *L;
	L=(Node *)malloc(sizeof(Node));
	if(L==NULL)
		printf("ERROR!\n");
	L->next=NULL;//初始化
}
  • 链表的创建(头插法):
Node* CreateHead()
{
	Node *L;
	L=(Node *)malloc(sizeof(Node));
	L->next=NULL;
	int x;
	int t=0;
	while(t!=6)//插6个
	{
		Node *p;
		p=(Node *)malloc(sizeof(Node));
		scanf("%d",&x);
		p->data=x;
		p->next=L->next;//在头结点处插入
		L->next=p;
		t++;
	}
	return L;
} 
  • 链表的创建(尾插法):
Node* CreateTail()
{
	Node *L;
	L=(Node *)malloc(sizeof(Node));
	L->next=NULL;
	Node *r=L;//该结点最后指向空
	int x;
	int t=0;
	while(t!=6)
	{
		Node *p;
		p=(Node *)malloc(sizeof(Node));
		scanf("%d",&x);
		p->data=x;
		r->next=p;//在已插结点的后面插
		r=p;
		t++;
	}
	r->next=NULL;
	return L;
}
  • 链表的插入:(在链表第i个结点处插入x元素)
Node* InsertList(Node *L,int i,int x)
{
	Node *p=L;
	int j;
	for(j=1;j<i;j++)//判断插入位置
	{
		p=p->next;
	}
	Node *q;
	q=(Node *)malloc(sizeof(Node));
	q->data=x;
	q->next=p->next;
	p->next=q;//插入
	return L;
}
  • 链表的删除:(删除链表中值为x的结点)
Node* DeleteList(Node *L,int x)
{
	Node *p,*q;
	p=L->next;
	while(p->data!=x)//判断删除结点位置
	{
		q=p;
		p=p->next;
	}
	q->next=p->next;//删除
	free(p);//释放
	return L;
}
  • 链表的输出:
void print(Node *L)
{
	Node *t;
	for(t=L->next;t!=NULL;t=t->next)
	{
		printf("%d  ",t->data);
	
  • 完整代码如下所示:
#include <stdio.h>
#include <stdlib.h>


typedef struct node
{
	int data;
	struct node *next;
}Node;

Node* InitList()
{
	Node *L;
	L=(Node *)malloc(sizeof(Node));
	if(L==NULL)
		printf("ERROR!\n");
	L->next=NULL;
}

Node* CreateHead()
{
	Node *L;
	L=(Node *)malloc(sizeof(Node));
	L->next=NULL;
	int x;
	int t=0;
	while(t!=6)
	{
		Node *p;
		p=(Node *)malloc(sizeof(Node));
		scanf("%d",&x);
		p->data=x;
		p->next=L->next;
		L->next=p;
		t++;
	}
	return L;
} 

Node* CreateTail()
{
	Node *L;
	L=(Node *)malloc(sizeof(Node));
	L->next=NULL;
	Node *r=L;
	int x;
	int t=0;
	while(t!=6)
	{
		Node *p;
		p=(Node *)malloc(sizeof(Node));
		scanf("%d",&x);
		p->data=x;
		r->next=p;
		r=p;
		t++;
	}
	r->next=NULL;
	return L;
}

Node* InsertList(Node *L,int i,int x)
{
	Node *p=L;
	int j;
	for(j=1;j<i;j++)
	{
		p=p->next;
	}
	Node *q;
	q=(Node *)malloc(sizeof(Node));
	q->data=x;
	q->next=p->next;
	p->next=q;
	return L;
}

Node* DeleteList(Node *L,int x)
{
	Node *p,*q;
	p=L->next;
	while(p->data!=x)
	{
		q=p;
		p=p->next;
	}
	q->next=p->next;
	free(p);
	return L;
}

void print(Node *L)
{
	Node *t;
	for(t=L->next;t!=NULL;t=t->next)
	{
		printf("%d  ",t->data);
	}
}

int main()
{
	Node *L,*t;
	printf("please input:\n");
	L=CreateTail();//创建链表
	print(L);
  	printf("\n");
	InsertList(L,3,9);//在链表的3个位置插入9这个元素
	printf("after Insert:\n");
	print(L);
	printf("\n");
	DeleteList(L,5);//删除值为5的这个结点
	printf("after Delete:\n");
	print(L);
 	return 0;
}
  • 运行结果如下:

猜你喜欢

转载自blog.csdn.net/qq_42735631/article/details/82766940