Re: 串列

作者: wwndbk (黑人問號)   2022-12-08 22:02:05
※ 引述《Sugarwithkis (sugarwithkis)》之銘言:
: 附合結構
: 指標
: 到底是三小
: 我是不是理解力有障礙
: 明明都有在聽課
: 要自己寫都不知道怎麼下手
: 嗚哇哇阿阿
:
:幫我寫一段用結構實作鏈結的c語言程式碼
#include <stdio.h>
#include <stdlib.h>
// 定義節點的結構體
struct Node {
int data; // 節點所保存的資料
struct Node *next; // 指向下一個節點的指標
};
// 定義鏈結串列的結構體
struct LinkedList {
struct Node *head; // 指向第一個節點的指標
struct Node *tail; // 指向最後一個節點的指標
};
// 初始化鏈結串列
void init(struct LinkedList *list) {
list->head = NULL;
list->tail = NULL;
}
// 在鏈結串列的最後添加一個新節點
void append(struct LinkedList *list, int data) {
// 建立新節點
struct Node *node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
// 如果鏈結串列為空,設定head和tail指向新節點
if (list->head == NULL) {
list->head = node;
list->tail = node;
}
// 否則,將tail的next指標指向新節點,並將tail指向新節點
else {
list->tail->next = node;
list->tail = node;
}
}
// 打印鏈結串列的所有元素
void printList(struct LinkedList *list) {
struct Node *current = list->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
// 建立鏈結串列
struct LinkedList list;
init(&list);
// 在鏈結串列末尾添加幾個節點
append(&list, 1);
append(&list, 2);
append(&list, 3);
append(&list, 4);
// 打印鏈結串列
printList(&list);
return 0;
}
雖然我看不懂在寫甚麼 對阿

Links booklink

Contact Us: admin [ a t ] ucptt.com