单链表的初始化、删除、添加 c++

根据下面博客学习的:

https://blog.csdn.net/Poxiao2017/article/details/80445145

https://blog.csdn.net/qq_41028985/article/details/82859199 

#include "stdafx.h"
#include "iostream"
using namespace std;

/* 单链表 */
typedef struct _LinkList{
	_LinkList(){ ; }
	int val;
	struct _LinkList *next;
}LinkList;

// 头插法初始化链表
LinkList* Creat_Head()
{
	LinkList *head, *node;
	int num;
	head = new LinkList;
	head->next = NULL;
	cout << "请输入,以0结束" << endl;
	cin >> num;
	while(num != 0)
	{
		node = new LinkList;
		node->val = num;
		node->next = head->next;
		head ->next = node;
		cin >> num;
	}
	return head;
}

//尾插法初始化链表
LinkList* Cread_End()
{
	LinkList *head, *node, *end;
	int num;
	head = new LinkList;
	head->next = NULL;
	end = head;
	cout << "请输入,以0结束" << endl;
	cin >> num;
	while (num != 0)
	{
		node = new LinkList;
		node->val = num;
		end->next = node;
		end = node;
		cin >> num;
	}
        end->next = NULL;       // 尾指针
	return head;
}

// 指定位置插入链表
void Insert(LinkList *first, LinkList *second, int n)
{
	int num = 0;
	LinkList *p = second;
	while((first->next != NULL) && (num < n)){
		first = first->next;
		num++;
	}
	while(second->next != NULL){
		second = second->next;
	}
	if(num == n){
		second->next = first->next;
		first->next = p->next;
	}
}

// 遍历链表
void Print_LinkList(LinkList *List)
{
	LinkList *node = List -> next;
	while (node != NULL)
	{
		cout << "list=" << node->val << "\n";
		node = node->next;
	}
}
// 获取链表结点个数
int Get_LinkList_Size(LinkList *List)
{
	int size = 0;
	LinkList *node = List->next;
	while (node != NULL){
		size++;
		node = node->next;
	}
	cout << "list结点个数为" << size << "\n";
	return size;
}
// 删除指定位置的节点
void Del_LinkList_val(LinkList *List, int n)
{
	int num = 0;
	int size = Get_LinkList_Size(List);
	LinkList *end;
	// 删除的位置大于或等于结点的个数,直接删除最后一个结点
	if(size <= n)
	{
		while ((List->next != NULL) && (num < n-1)){
			List = List->next;
			num++;
		}
		end = List->next;
		List->next = NULL;
		free(end);
	}
	else
	{
		while ((List->next != NULL) && (num < n)){
			List = List->next;
			num++;
		}
		if (n == num)
		{
			end = List->next;
			List->next = end->next;
			free(end);
		}
	}
	

}

int _tmain(int argc, _TCHAR* argv[])
{
	LinkList *list1 = Creat_Head();
	//LinkList *list2 = Cread_End();
	//Insert(list1, list2, 2);
	//Print_LinkList(list1);
	Del_LinkList_val(list1, 2);
	Print_LinkList(list1);
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值