1. 程式人生 > 實用技巧 >寫一個函式insert,用來向一個動態連結串列插入結點

寫一個函式insert,用來向一個動態連結串列插入結點

寫一個函式insert,用來向一個動態連結串列插入結點

#include <stdio.h>
#include <stdlib.h>

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

void insert(int n, LNode *node)
{
	//建立新節點
	LNode *newNode = (LNode *)malloc(sizeof(LNode));
	newNode->num = n;

	LNode* next = node->next;

	// node ---> newNode  ---> next
	newNode->next = next;
	node->next = newNode;
}

LNode* creat(int n)
{
	LNode *head, *p;
	head = (LNode *)malloc(sizeof(LNode));
	p = head; //頭節點為0 加上頭節點共11個節點
	head->num = 0;
	head->next = NULL;
	for (int i = 1; i <= n; i++)
	{
		LNode *newNode = (LNode *)malloc(sizeof(LNode));
		newNode->num = i;
		newNode->next = NULL;
		p->next = newNode;
		p = p->next;
	}
	return head;
}

void printNode(LNode* head)
{
	LNode* p = head->next;
	while (p != NULL)
	{
		printf("num -> %d\n", p->num);
		p = p->next;
	}
}

int main()
{
	LNode *head;
	int n;
	head = creat(10);
	printNode(head);
	printf("請輸入需要插入的節點:\n");
	scanf("%d", &n);
	insert(n, head);
	printf("連結串列的新內容:\n");
	printNode(head);
	return 0;
}

執行截圖: