學習了數據結構后,自己學習寫了一個鏈表的程序。
初步功能是實現了。但是不知道會不會有一些隱含的問題。所以希望大佬指導指導
/******************/ /*一個小的鏈表程序*/ /******************/ #include <stdio.h> #include <stdlib.h> //結點的結構體 typedef struct node { char data; struct node*next; }Node; //鏈表的結構體 typedef struct { Node *head; Node *list1; int num; }NList; //生成一個鏈表 void CreateList(NList *list) { list->head = NULL; list->list1 = NULL; list->num = 0; } //向鏈表中添加數據 void AddList(NList *list) { char data; scanf("%c",&data); while(data != '#') { if(list->head == NULL) { list->head = (Node *)malloc(sizeof(Node)); list->head->data = data; list->head->next = NULL; list->list1 = list->head; list->num = 1; } else { Node *p = (Node *)malloc(sizeof(Node)); list->list1->next = p; p->data = data; list->list1 = p; list->list1->next = NULL; list->num++; } scanf("%c",&data); } } //顯示鏈表中的數據 void ShowList(NList list) { Node *P1; P1=list.head; while(P1 != NULL) { printf("%c",P1->data); P1 = P1->next; } } //刪除鏈表頭的數據 void DelList_head(NList *list) { if(list->head != NULL) { Node *p2 = list->head; list->head = p2->next; list->num--; free(p2); } else { printf("鏈表中不存在數據\n"); } } int main() { NList list2; CreateList(&list2); AddList(&list2); ShowList(list2); printf("\n鏈表中的數據個數是:%d個\n",list2.num); DelList_head(&list2); ShowList(list2); printf("\n鏈表中的數據個數是:%d個\n",list2.num); return 0; }
程序的執行結果如下:
另一個更加優化的鏈表代碼,注釋思路更加清晰:
#include <stdio.h>
#include <stdlib.h>
//結點的結構
typedef struct Node
{
int data;
struct Node *link;
}node;
//創建一個頭結點
node * create_list(int x)
{
node *p = (node *)malloc(sizeof(node));
p->data = x;
p->link = NULL;
return p;
}
//向鏈表中添加數據
void add_list(node * head,int x)
{
if(!head)return;
while(head->link)
head = head->link;
node *p = (node *)malloc(sizeof(node));
p->data = x;
p->link = NULL;
head->link = p;
}
//在鏈表中查找數據
node * find_list(node * head,int x)
{
while(head && head->data != x)
head = head->link;
if(head) return head;
return NULL;
}
//打印鏈表中的數據
void show_list(node * head)
{
while(head)
{
printf("%d->",head->data);
head = head->link;
}
printf("null\n");
}
//反轉鏈表
node * reverse(node * head)
{
node * new = NULL,*old = head,*temp;
while(old)
{
temp = old->link;
old->link = new;
new = old;old = temp;
}
return new;
}
//刪除鏈表頭節點
node * del_list(node * head)
{
if(!(head))return NULL;
node *p = (head);
(head) = (head)->link;
free(p);
return head;
}
//刪除鏈表,需要修改head的指向,所以使用二級指針
void del_list_all(node **head)
{
while((*head))
(*head) = del_list((*head));
}
//測試程序
int main()
{
node *ptr = create_list(1);
add_list(ptr,2);
add_list(ptr,3);
add_list(ptr,4);
show_list(ptr);
if(find_list(ptr,5)) printf("查找到3的節點\n");
else printf("未找到3的節點\n");
if((ptr = del_list(ptr)) == NULL) printf("該鏈表為空鏈表,不可刪除\n");
show_list(ptr);
del_list_all(&ptr);
show_list(ptr);
return 0;
}