数据结构(单链表)

// main.h
#pragma once
#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

//定义一个单链表结构
struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL){}
	ListNode() : next(NULL){}
};

//创建一个单链表
//按插入创建,比如输入1回车2回车3回车4回车NULL得到的是1->4->3->2
ListNode* createList1()
{
	ListNode* pList = NULL;
	string sValue = "";
	while (cin>>sValue)
	{
		if (sValue=="NULL")
		{
			break;
		} 
		else if (!pList)
		{
			pList = new ListNode();
			pList->val = stoi(sValue);
		}
		else
		{
			ListNode* pNewNode = new ListNode();
			pNewNode->val = stoi(sValue);
			pNewNode->next = pList->next;
			pList->next = pNewNode;
		}
	}
	return pList;
}

//按后序创建比如:输入为1回车2回车3回车NULL,输出的链表为1<-2<-3
ListNode* createList2()
{
	string sValue = "";
	ListNode* pOldNode = NULL;
	ListNode* pNewNode = NULL;
	while (cin >> sValue)
	{
		if (sValue == "NULL")
		{
			break;
		}
		else if (!pOldNode)
		{
			pOldNode = new ListNode();
			pOldNode->val = stoi(sValue);
		}
		else
		{
			pNewNode = new ListNode();
			pNewNode->val = stoi(sValue);
			pNewNode->next = pOldNode;
			pOldNode = pNewNode;
		}
	}
	return pNewNode;
}

//按顺序创建比如输入为1回车2回车3回车NULL创建的链表为1->2->3
ListNode* createList3()
{
	string sValue = "";
	ListNode* pLists = NULL;
	ListNode* pIndex = NULL;
	while (cin >> sValue)
	{
		if (sValue == "NULL")
		{
			break;
		}
		else if (!pLists)
		{
			pLists = new ListNode();
			pLists->val = stoi(sValue);
			pIndex = pLists;
		}
		else
		{
			ListNode* pNodes = new ListNode();
			pNodes->val = stoi(sValue);
			pIndex->next = pNodes;
			pIndex = pNodes;
		}
	}
	return pIndex;
}

//,每次输入一个数字不需要按回车键,比如输入1 2 3回车,得到的是1->2->3
ListNode* createList4()
{
	ListNode* pList = NULL;
	ListNode* pIndex = NULL;

	int iValue = 0;
	while (scanf_s("%d", &iValue))
	{
		if (!pList)
		{
			pList = new ListNode();
			pIndex = pList;
			pList->val = iValue;
		}
		else
		{
			ListNode* pNewNode = new ListNode();
			pNewNode->val = iValue;
			pIndex->next = pNewNode;
			pIndex = pNewNode;
		}
		char cEnd = getchar();
		if (cEnd=='\n')
		{
			break;
		}
	}
	return pList;
}

//将链表数据全部打印出来
void printfList(ListNode* l)
{
	ListNode* l_index = l;
	while (l_index)
	{
		cout << l_index->val << endl;
		l_index = l_index->next;
	}
}
// main.cpp
#include "main.h"
void main()
{
	ListNode* l = createList1();
	printfList(l);
	return;
}

//输入
在这里插入图片描述
//输出
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值