1. 程式人生 > 實用技巧 >Java列舉類的使用

Java列舉類的使用

在第9章例9.9和例9.10的基礎上,寫一個函式del,用來刪除動態連結串列中指定的節點

解題思路:

首先建立一個帶頭的單鏈表,然後讓使用者輸入需要刪除的節點,呼叫del函式,找到需要刪除的節點,把待刪除節點的前驅和後繼重新連結。

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

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

//建立含有n個值的節點
LNode* creat(int n)
{
	LNode *head, *p;
	head = (LNode *)malloc(sizeof(LNode));
	p = head; //頭節點為0 加上頭節點共n + 1個節點
	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;
}

//刪除值為n的節點
void del(int n, LNode *head)
{
	LNode *pre, *current;
	pre = head;
	current = head->next;
	//從第一個有效節點開始查詢待刪除節點
	printf("delete node %d\n", n);
	while (current != NULL)
	{
        //找到待刪除節點,重新連結,釋放待刪除節點
		if (current->num == n)
		{
			pre->next = current->next;
            free(current);
			break;
		}
        //更新查詢位置
		pre = current;
		current = current->next;
	}
}

int main()
{
	LNode *head, *p;
	int n;
	head = creat(10);
	printf("請輸入需要刪除的節點:1-10\n");
	scanf("%d", &n);
	del(n, head);
	int i = 1;
	p = head->next;
	while (p != NULL)
	{
		printf("p %d.num -> %d\n", i, p->num);
		p = p->next;
		i++;
	}
	return 0;
}

執行截圖: