数据结构单链表之(一)初始化&&尾插&&显示表
作者:互联网
文章目录
前言
开始单链表!!!
1. 目标
printf("* [1] push_back [2] push_front *\n");
printf("* [3] show_list [4] pop_back *\n");
printf("* [5] pop_front [6] insert_val *\n");
printf("* [7] find [8] length *\n");
printf("* [9] delete_val [10] sort *\n");
printf("* [11] resver [12] clear *\n");
printf("* [13] destroy [0] quit *\n");
实现单链表的这些功能
2. 思路
2.1 初始化
一个节点:包括数据和指向下一个节点的指针
一个单链表:first指向头节点,头结点不存储值,存储指向第一个节点的指针;last指向尾节点,尾节点的下一个节点为NULL;size表示除头结点以外的节点数。
因此对于单链表的初始化应包含对节点和链表的定义,另外让last也指向头结点,size为0
2.2 尾插
2.3 显示表
2. 代码
2.1 Sqlist.h
#ifndef _SLIST_H_
#define _SLIST_H_
#define ElemType int
typedef struct Node
{
ElemType data;
struct Node *next;
}Node, *PNode;
typedef struct List
{
PNode first;
PNode last;
int size;
}List;
//初始化链表
void InitList(List *list);
//尾部插入
void push_back(List *list, ElemType x);
//显示链表
void show(List *list);
#endif //_SLIST_H_
2.2 Sqlist.cpp
#include "SList.h"
#include <stdio.h>
#include <assert.h>
#include <malloc.h>
void InitList(List *list)
{
list->first = list->last = (Node *)malloc(sizeof(Node));
assert(list->first != NULL);
list->size = 0;
}
void push_back(List *list, ElemType x)
{
Node *s = (Node *)malloc(sizeof(Node));
assert(s != NULL);
s->data = x;
s->next = NULL;
list->last->next = s;
list->last = s;
list->size++;
}
void show(List *list)
{
Node *p = list->first->next;
while(p != NULL)
{
printf("%d-->", p->data);
p = p->next;
}
printf("NUL\n");
}
2.3 main
#include "SList.h"
#include <stdio.h>
int main()
{
List mylist;
InitList(&mylist);
Node *p = NULL;
ElemType Item;
int select = 1;
while(select)
{
printf("*********************************\n");
printf("* [1] push_back [2] push_front *\n");
printf("* [3] show_list [4] pop_back *\n");
printf("* [5] pop_front [6] insert_val *\n");
printf("* [7] find [8] length *\n");
printf("* [9] delete_val [10] sort *\n");
printf("* [11] resver [12] clear *\n");
printf("* [13] destroy [0] quit *\n");
printf("*********************************\n");
printf("请选择:>");
scanf("%d", &select);
switch(select)
{
case 1:
printf("请输入要插入的数据(-1结束):");
while(scanf("%d",&Item), Item != -1)
{
push_back(&mylist, Item);
}
break;
case 3:
show(&mylist);
break;
default:
break;
}
}
return 0;
}
3. 结果
总结
接下来做头插,尾删和头删。
标签:Node,单链,List,list,back,表之,&&,printf,push 来源: https://blog.csdn.net/YL950305/article/details/116424363