数据结构 链表的基本操作

概念区分:

头结点和头指针
通常使用头指针来标识一个链表,如单链表L,头指针为NULL时表示一个空表。
为了操作上的方便,在单链表第一个节点之前添加一个头结点。头结点的额指针域指向线性表的第一个元素节点。
不管带不带头结点,头指针总是指向链表的第一个节点。头结点是带头结点链表的第一个节点。

基本操作

创建链表
链表长度
查找元素
插入数据
删除数据

  • 创建链表
//2020/4/4
#include<stdio.h>
#include<stdlib.h>

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

//建立含有头结点的链表
Node* create(int A[])
{
	Node *head,*p,*s;//head头指针、p、q用于表示关系,s表示新建节点

	head = (Node*)malloc(sizeof(Node));
	head->next = NULL;

	p = head;

	for(int i = 0;i<8;i++)//尾插法
	{
		s = (Node*)malloc(sizeof(Node));
		s->data = A[i];
		s->next = NULL;
		p->next = s;
		p = s;
	}
	return head;
}

int find(Node* head,int x)
{
	int count = 0;
	Node *p;
	p = head->next;
	while(p)
	{
		if(p->data == x)
			count++;
		p = p->next;
	}
	return count;
}

void insert_pos(Node *head,int pos,int x)
{
	int i;
	Node *p,*s;
	p = head;
	for(i = 0;i<pos-1;i++)//寻找插入位置的前一个元素
	{
		p = p->next;
	}

	s = (Node*)malloc(sizeof(Node));
	s->data = x;
	s->next = p->next;
	p->next = s;
}

void insert_head(Node *head,int x)
{
	Node *p,*s;
	p = head;

	s = (Node*)malloc(sizeof(Node));
	s->data = x;

	s->next = p->next;
	p->next = s;
}

void insert_rear(Node* head,int x)
{
	Node *p,*s;
	p = head;
	while(p)
	{
		if(p->next == NULL)
			break;
		else p = p->next;
	}

	s = (Node*)malloc(sizeof(Node));
	s->data = x;
	s->next = NULL;

	p->next = s;
}

void del_one(Node* head,int x)
{
	Node *p,*q;
	p = head->next;//指向第一个元素节点
	q = head;

	while(p)
	{
		if(p->data == x)
		{
			q->next = p->next;
			free(p);
			break;
		}
		else
		{
			q = p;
			p = p->next;
		}
	}
}

void del_all(Node* head,int x)
{
	Node *p,*q;
	p = head->next;
	q = head;
	while(p)
	{
		if(p->data == x)
		{
			q->next = p->next;
			free(p);
			p = q->next;
		}
		else
		{
			q = p;
			p = p->next;
		}
	}
}

int isEmpty(Node* head)
{
	if(head->next == NULL)
		return 1;
	else return 0;
}

int len(Node *head)
{
	int count = 0;
	Node* p =head->next;
	while(p)
	{
		count++;
		p = p->next;
	}
	return count;
}


void print(Node* head)
{
	Node *p;
	p = head->next;
	while(p)
	{
		if(p->next == NULL)
			printf("%d\n",p->data);
		else printf("%d ",p->data);
		p = p->next;
	}
}

int main()
{
	int A[8] = {1,2,3,4,5,6,7,7};
	Node* head = create(A);
	print(head);

	insert_pos(head,8,1);
	print(head);

	insert_head(head,7);
	print(head);

	insert_rear(head,1);
	print(head);

	del_one(head,1);
	print(head);

	del_all(head,1);
	print(head);

	printf("%d\n",isEmpty(head));
	printf("%d\n",len(head));




	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值