單向鏈表
在上一回可變數組的文末闡述了可變數組的缺點。鏈表針對同一需求就很好的彌補了可變數組的缺點。其結構如下圖:
在單鏈表分爲頭部*head
指針,和後續節點兩個部分。在每個節點中也有兩個部分,分別用於是存放數值(圖中value
的部分),及指向下一個節點的next
指針。head
指針剛開始爲空,在添入第一個節點後,指向第一個節點。當節點的next
指向NULL時,表示該節點當前沒有後繼節點。
構造單向鏈表
使用結構體表示鏈表的單個節點
typedef struct _node{
int value;
struct _node *next;
} Node;
構造鏈表
typedef struct _list {
Node *head;
} List;
實現單向鏈表
實現的功能包括:添加元素、打印所有元素、查詢元素、刪除元素、清空鏈表。
可執行代碼如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct _node{
int value;
struct _node *next;
} Node;
typedef struct _list {
Node *head;
} List;
void add(List *pList, int number)//添加
{
// add to linked-list
Node *p = (Node*)malloc(sizeof(Node));
p->value = number;
p->next = NULL;
// find the last
Node *last = pList->head;
if(last)
{
while(last->next)
last = last->next;
// attach
last->next = p;
}
else
pList->head = p;
}
void print(List *pList)//打印鏈表所有元素
{
Node *p;
for (p=pList->head; p; p=p->next)
printf("%d\t", p->value);
printf("\n");
}
int found(List *pList, int number)//查詢元素是否在鏈表內
{
Node *p;
int isFound = 0;
for(p=pList->head; p; p=p->next)
{
if(p->value == number)
{
printf("is found\n");
isFound = 1;
break;
}
}
if(!isFound)
{
printf("NO found\n");
return 0;
}
else
return 1;
}
void Remove(List *pList, int number)//刪除元素
{
Node *p, *q;
for(q=NULL, p=pList->head; p; q=p, p=p->next)
{
if(p->value == number)
{
if(q)
q->next = p->next;
else
pList->head = p->next;
free(p);
break;
}
}
}
void empty(List *pList)//清空鏈表
{
Node *p, *q;
for (p=pList->head; p; p=q)
{
q = p->next;
free(p);
}
pList->head = NULL;
}
int main(int argc, char const *argv[])
{
List list;
int number;
list.head = NULL;
//向鏈表中添加元素,直到輸入-1結束
do {
scanf("%d",&number);
if(number != -1)
add(&list, number);
} while(number != -1);
print(&list);
//輸入一個數,查詢這個數是否在鏈表中,是則刪除這個數。 直到輸入-1結束
while(1)
{
scanf("%d", &number);
if(number != -1)
{
if(found(&list, number))
Remove(&list, number);
print(&list);
}
else break;
}
empty(&list);
//驗證鏈表是否被清空
if(list.head == NULL)
printf("list was emptied!\n");
return 0;
}