寫一個函數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;
}

運行截圖:

寫一個函數insert,用來向一個動態鏈表插入結點


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM