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

单链表的基本操作

程序员文章站 2024-03-05 23:44:19
...

单链表的基本操作

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define NODE struct Node
struct Node
{
	char *name;
	NODE *next;
};
NODE *Creat_Linklist(char *p[], int n);
void Print_List(NODE *head);
NODE *Insert_Linklist(NODE *head,int n);
NODE *Delet_Linklist(NODE *head, char *na);
int main()
{
	char *na;
	na = (char *)malloc(20);
	NODE *head;
	char *p[6] = { "wangli","xiaoming","lilei","zhishiteng","mirunyang","yuanzhicai" };
	head=Creat_Linklist(p, 6);
	head=Insert_Linklist(head, 2);
	Print_List(head);
	printf("请输入要删除的节点的姓名:");
	scanf_s("%s", na, 20);
	head=Delet_Linklist(head, na);
	Print_List(head);
}

NODE *Creat_Linklist(char *p[], int n)//创建单链表,单链表带头节点
{
	NODE *head, *tail, *new_Node;
	head = (NODE*)malloc(sizeof(NODE));
	new_Node= (NODE*)malloc(sizeof(NODE));
	new_Node->name = p[0];
	head->next = new_Node;
	tail = new_Node;
	for (int i = 1;i < 6;i++)
	{
		new_Node = (NODE*)malloc(sizeof(NODE));
		new_Node->name = p[i];
		tail->next = new_Node;
		tail = new_Node;
	}
	tail->next = NULL;
	printf("单链表创建成功\n");
	return head;
}
NODE *Insert_Linklist(NODE *head,int n)//向链表中插入元素
{
	char *na;
	na = (char*)malloc(20);
	NODE *p;
	p = head;
	printf("请输入一个名字:");
	scanf_s("%s", na, 20);
	NODE *new_one;
	new_one = (NODE*)malloc(sizeof(NODE));
	new_one->name = na;
	switch (n)
	{
	case 1:
		   printf("插入到链表的最前面\n");
		   p = p->next;
		   new_one->next = p;
		   head->next = new_one;
	case 2:
		printf("插入到名字叫支世腾的后面\n");
		NODE *q, *m;
		q = head;
		for (q; ; )
		{
			q = q->next;
			if (strcmp(q->name,"zhishiteng") == 0)
			{
				m = q->next;
				new_one->next = m;
				q->next = new_one;
				break;
			}

		}
	case 3:
	default:
		break;
	}
	return head;
}
NODE *Delet_Linklist(NODE *head, char *na)//删除姓名为。。。的节点
{
	NODE *p, *q;
	p = head;
	for (p; ; )
	{
		q = p;
		p = p->next;
		if (strcmp(p->name, na) == 0)
		{
			q->next = p->next;
			break;
		}
	}
	return head;
}
void Print_List(NODE *head)//遍历单链表
{
	NODE *p;
	p = head;
	p = p->next;
	printf("数组中所存储的名字分别为:");
	for (int i = 0;i < 10;i++)
	{
		printf("%s  ", p->name);
		p = p->next;
		if (p == NULL)
			break;
	}
}