链表(二)——单向链表的基本操作(创建、删除、打印、结点个数统计)

1.指针的联动
通过两个指针分别指向前驱和后继结点,并在单向链表上进行移动,当指针指向待处理的结点时,该结点的前驱也有指针指向。
2.设有一个无序单向链表,且数据域的值均不相同,使指针pmin指向最小值结点,并使指针prem指向最小值结点的前驱结点:
代码片段:
for(p = head; p; q = p, p = p->next)
{
    if(pmin->data > p->data)
    {
        pmin = p;
        prem = q;
    }
}
3.单向链表的删除算法
注:使用malloc函数分配的结点单元必须使用free函数来释放,free(p)之后,p所指向的单元被释放,p被系统重新赋值为随机值,p只能在程序运行完成之后自动清除。
头结点的删除:head = head->next;free(pdel);
非头结点的删除:ppre->next = pdel->next;free(pdel);
4.例子
注:单向链表的最基本的操作,新建一个链表、删除一个元素、打印链表、统计链表的个数、删除链表。

#include 
#include 

#define NULL	0

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


ElemSN * creat_link(int ms); //逆向创建一个链表
void print_link(ElemSN *head); //输出单向链表
ElemSN * delete_node(ElemSN *head, int x); //删除链表中的一个结点
int count_link(ElemSN *head); //统计单向链表结点的个数
ElemSN * clear_link(ElemSN *head); //删除链表

int main()
{
	ElemSN *head;
	int ms, x;

	printf("Please input node number:");
	scanf("%d", &ms);
	head = creat_link(ms);
	print_link(head);
	printf("Please input delete node:");
	scanf("%d", &x);
	head = delete_node(head, x);
	print_link(head);
	printf("link member is :%d\n", count_link(head));
	head = clear_link(head);
}

ElemSN * creat_link(int ms)
{
	ElemSN *h = NULL, *p;
	int i, x;

	for(i = 0; i < ms; i++)
	{
		printf("Please input data:");
		scanf("%d", &x);
		p = (ElemSN *)malloc(sizeof(ElemSN));
		p->data = x;
		p->next = h;
		h = p;
	}

	return h;
}

void print_link(ElemSN *head)
{
	for(; head; head = head->next)
	{
		printf("%d ", head->data);
	}
	printf("\n");
}

ElemSN * delete_node(ElemSN *head, int x)
{
	ElemSN *p = NULL, *q = NULL;
	
	if(NULL == head)
	{
		return NULL;
	}
	for(p = head; p && p->data != x; q = p, p = p->next); //p && p->data != x不能交换位置

	if(NULL == p) //没有找到要删除的结点
	{
		return head;
	}

	if(NULL == q) //要删除的是头结点
	{
		head = head->next;
	}
	else
	{
		q->next = p->next;
	}
	free(p);

	return head;
}

int count_link(ElemSN *head)
{
	int count = 0;
	
	for(; head; count++, head = head->next);

	return count;
}

ElemSN * clear_link(ElemSN *head)
{
	ElemSN *p;

	while(head)
	{
		p = head->next;
		free(head);
		head = p;
	}

	return head;
}

你可能感兴趣的:(编程与算法,单向链表,创建链表,删除链表)