// 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;
}
//输入
//输出