数据结构 --- 线性表(单链表)

工程目录结构:

common.h:

 1 #define OK 1
 2 #define ERROR 0
 3 #define TRUE 1
 4 #define FALSE 0 
 5 typedef int Status;
 6 
 7 #pragma region 单链表
 8 
 9 //线性表的单链表存储结构
10 typedef struct Node
11 {
12     int data;
13     struct Node *next;
14 }Node;
15 
16 typedef struct Node *LinkList;   //定义LinkList
17 
18 #pragma endregion

LinkList.c:

 1 #include "common.h"
 2 #include <stdio.h>
 3 #include <malloc.h>
 4 
 5 //在L的第i个位置,插入元素e
 6 Status LinkListInsert(LinkList L, int i, int e)
 7 {
 8     LinkList p;
 9 
10     //搜索第i个结点
11     p = L;
12     
13     int index = 1;
14     while (p && index < i)
15     {
16         p = p->next;
17         ++index;
18     }
19 
20     if (!p || index > i)
21     {
22         printf("结点搜索失败!");
23         return ERROR;
24     }
25 
26     //生成新结点,并插入到 L
27     LinkList s = (LinkList)malloc(sizeof(Node)); 
28     s->data = e;
29     s->next = p->next;
30     p->next = s;
31     return OK;
32 }

main.c:

 1 #include<stdio.h>
 2 #include<malloc.h>
 3 #include "common.h"
 4 
 5 Status LinkListInsert(LinkList L, int i, int e);
 6 
 7 int main()
 8 {
 9     LinkList L = (LinkList)malloc(sizeof(Node));  //带有头结点
10     L->data = -1;
11     L->next = NULL;
12 
13     for (int i = 1; i <= 5; ++i)
14     {
15         if (OK == LinkListInsert(L, i, i * 2))
16             printf("位置: %d, 元素: %d\n", i, i * 2);
17     }
18 
19     printf("\n\n打印元素:\n");
20 
21     LinkList fist = L->next;
22     while (fist != NULL)
23     {
24         printf("%d, ", fist->data);
25         fist = fist->next;
26     }
27 
28     printf("\n");
29 
30     getchar();
31     return 0;
32 }

猜你喜欢

转载自www.cnblogs.com/luguoshuai/p/9244823.html
今日推荐