Link List算是基礎資料結構的練習 , Embedded System因為資源有限 , 會比較常用 ~
這種東西說難不難 , 但久沒用還真的會有點忘記 , 所以照慣例筆記一下 ^^
=====================================================
下面是一個Link List練習題 ,
(1) 產生5個nodes , 分別為a,b,c,d,e , 其內容各為5,6,8,9,10
(2) 在node b 與 node c之間插入node b1 , 其內容為7
(3) 刪除 node b
程式原始碼
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int iData;
struct node* pNext;
}TNode;
TNode* Create_node( int iData )
{
TNode* ptr_Node = (TNode*)malloc(sizeof(TNode));
ptr_Node->iData = iData;
ptr_Node->pNext = NULL;
return ptr_Node;
}
void Insert_node(TNode* n1, TNode* n2)
{
// Insert n2 between n1 and n1 original next
n2->pNext = n1->pNext; // n2 next = n1 original next
n1->pNext = n2; // n1 netx = n2
}
void Remove_node(TNode* n1)
{
n1->pNext = n1->pNext->pNext; // n1 netx = n2's next
}
int main()
{
// Create 5 nodes , that is "5 6 8 9 10"
TNode* a = Create_node(5);
TNode* b = Create_node(6);
TNode* c = Create_node(8);
TNode* d = Create_node(9);
TNode* e = Create_node(10);
// Setup Link List
a->pNext = b;
b->pNext = c;
c->pNext = d;
d->pNext = e;
e->pNext = NULL;
printf("(1)Link List : %d -> %d -> %d -> %d -> %d \n" ,a->iData
,a->pNext->iData
,a->pNext->pNext->iData
,a->pNext->pNext->pNext->iData
,a->pNext->pNext->pNext->pNext->iData);
// 1. Insert node between 6 and 8 and data is 7
TNode* b1 = Create_node(7);
Insert_node(b,b1);
printf("(2)Link List : %d -> %d -> %d -> %d -> %d -> %d\n" ,a->iData
,a->pNext->iData
,a->pNext->pNext->iData
,a->pNext->pNext->pNext->iData
,a->pNext->pNext->pNext->pNext->iData
,a->pNext->pNext->pNext->pNext->pNext->iData);
// 2. Remove node between 8 and 10 , that is "5 6 7 8 10"
Remove_node(c);
printf("(3)Link List : %d -> %d -> %d -> %d -> %d \n" ,a->iData
,a->pNext->iData
,a->pNext->pNext->iData
,a->pNext->pNext->pNext->iData
,a->pNext->pNext->pNext->pNext->iData);
system("pause");
return 0;
}
程式執行結果
留言列表