主要包含:
单链表的数据结构,初始化,打印输出,建立单链表(尾插法),元素按位插入,按位删除,按值查找。
- #include
- #include
- #include
-
- #define MAXSIZE 100
- #define ElemType int
- #define Status int
-
- //单链表的数据结构
- typedef struct LNode
- {
- ElemType data;
- struct LNode *next;
- }LNode, *LinkList;
-
- //初始化
- int InitList(LinkList &L)
- {
- L = (LNode *)malloc(sizeof(LNode));
- L->next = NULL;
- return 1;
- }
-
- //输出
- void PrintList(LinkList L)
- {
- printf("当前单链表的所有元素:");
- LNode *p;
- p = L->next;
- while (p != NULL)
- {
- printf("[%d] ", p->data);
- p = p->next;
- }
- printf("\n");
- }
-
- //尾插法创建单链表
- int Create(LinkList &L)
- {
- int n, e;
- LNode *temp = L;//声明一个指针指向头结点,用于遍历链表
-
- printf("请输入要输入元素的个数:");
- scanf("%d", &n);
- for (int i = 1; i <= n; i++)
- {
-
- LNode *a = (LNode*)malloc(sizeof(LNode));
- printf("请输入第%d元素的值:", (i));
- scanf("%d", &e);
- a->data = e;
- temp->next = a;
- a->next = NULL;
- temp = temp->next;
- }
- return 1;
- }
-
- //插入元素
- int InsertList(LNode *L, int i, ElemType e)
- {
- LNode *p = L;
- int j = 0;
- while (p && (j < i - 1)) //寻找要插入位置的前驱结点,让p指向它
- {
- p = p->next;
- ++j;
- }
- if (!p || j > i - 1) return 0; //插入位置非法,返回0
- LNode *s = (LNode *)malloc(sizeof(LNode));
- s->data = e; //创建一个新结点存放要插入的元素e
- s->next = p->next; //把新结点的指针域指向p->next
- p->next = s; //把p->next指向要插入的新结点
- return 1;
- }
-
- //删除元素
- int DeleteList(LNode *L, int i)
- {
- LNode *p = L;
- int j = 0;
- while (p->next && (j < i - 1)) //寻找要删除结点的前驱结点,让p指向它
- {
- p = p->next;
- ++j;
- }
- if (!p->next || j > i - 1) return 0; //删除位置非法,返回0
- LNode *q;
- q = p->next; //暂存删除结点,以便随后释放
- p->next = q->next; //把p->next指向p->next->next,即q->next
- free(q); //释放结点
- return 1;
- }
-
- //按值查找元素
- int LocateElem(LNode *L, ElemType e)
- {
- int i = 1;
- LNode *p = L->next;
- while (p&&p->data != e) //从第一个结点开始,依次向后遍历比较
- {
- p = p->next;
- i++;
- }
- if(p) return i;
- else return 0;
- }
-
- int main(){
- LinkList L;
- InitList(L);
- Create(L);
- PrintList(L);
- InsertList(L, 4, 5);
- PrintList(L);
- DeleteList(L, 3);
- PrintList(L);
- printf("%d\n",LocateElem(L, 2));
- return 0;
- }
输出:
- 请输入要输入元素的个数:5
- 请输入第1元素的值:1
- 请输入第2元素的值:2
- 请输入第3元素的值:3
- 请输入第4元素的值:4
- 请输入第5元素的值:5
- 当前单链表的所有元素:[1] [2] [3] [4] [5]
- 当前单链表的所有元素:[1] [2] [3] [5] [4] [5]
- 当前单链表的所有元素:[1] [2] [5] [4] [5]
- 2