数据结构单链表之(一)初始化&&尾插&&显示表

前言

开始单链表!!!

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 SList.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 SList.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. 结果

在这里插入图片描述

总结

接下来做头插,尾删和头删。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值