C語言的單向鏈表代碼

寫着玩 

#include <stdio.h>

typedef struct Node
{
	int num;
	struct Node *next;
} Node;

Node *head=NULL;
int count = 0;

void addNode()
{
	int num;
	Node *p = (Node*)malloc(sizeof(Node));

	printf("please input a number to the list: ");
	scanf_s("%d", &num);


	p->num = num;
	p->next = NULL;

	if (head == NULL)
	{
		head = p;
	}
	else
	{
		Node *temp;
		temp = head;
		while ((*temp).next != NULL)
		{
			temp = temp->next;
		}
		temp->next = p;
	}
	count++;
}

void modifyNode()
{
	int index;
	int num;
	int i;
	Node *p = head;

	printf("please input the index of the list: ");
	scanf_s("%d", &index);

	if (index > count)
	{
		printf("the length is not enough.\n");
	}
	else
	{
		printf("please input the num of the node: ");
		scanf_s("%d", &num);

		for (i = 0; i < index; i++)
		{
			p = p->next;
		}
		if (p == NULL)
		{
			printf("Error index");
		}
		else
		{
			(*p).num = num;
		}
	}
}

void insertNode()
{
	int index, num, i;
	Node *p = head;
	Node *temp;

	printf("please input the index: \n");
	scanf_s("%d", &index);

	printf("please input the num: \n");
	scanf_s("%d", &num);
	if (index > count)
	{
		printf("Error index!");
	}
	else
	{
		for (i = 0; i < index; i++)
		{
			p = p->next;
		}
		//下一個節點的地址
		temp = p->next;

		Node *pnNode = (Node*)malloc(sizeof(Node));
		pnNode->num = num;
		pnNode->next = temp;
		p->next = pnNode;	
		count++;
	}
}

void removeNode()
{
	int index, i;
	Node *p = head;
	
	printf("please input the deleting index: ");
	scanf_s("%d", &index);

	if (index > count)
	{
		printf("Error index!");
	}
	else
	{
		for (i = 0; i < index-1; i++)
		{
			p = p->next;
		}
		Node *temp = p->next->next;
		Node *deletingNode = p->next;

		p->next = temp;

		free(deletingNode);
		count--;
	}
}

void clearList()
{
	Node *p1, *p2;
	p1 = head;
	p2 = p1->next;
	do
	{
		free(p1);
		p1 = p2;
		if (p1 != NULL)
		{
			p2 = p1->next;
		}
	} while (p1 != NULL);

	head = NULL;
	count = 0;
}

void main()
{
	int funNum = 0;
	Node *p;

	while (funNum != -1)
	{
		printf("please select the functions:\n");
		printf("1 add a node\n");
		printf("2 moidy a node\n");
		printf("3 insert a node\n");
		printf("4 remove a node\n");
		printf("5 clear the list\n");
		printf("-1 exit\n");

		scanf_s("%d", &funNum);

		switch (funNum)
		{
		case 1:
			addNode();
			break;
		case 2:
			modifyNode();
			break;
		case 3:
			insertNode();
			break;
		case 4:
			removeNode();
			break;
		case 5:
			clearList();
			break;
		case -1:
			break;
		default:
			printf("Wrong Number!\n");
			break;
		}

		printf("\nThe content of the list is: ");
		if (head != NULL)
		{
			p = head;

			do{
				printf("%d ", (*p).num);
				p = p->next;
			} while (p != NULL);
		}
		printf("\n\n");
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章