您的位置:首页 > 其它

创建无头结点单链表

2018-04-01 23:23 232 查看
#include "stdafx.h"
#include <iostream>
using namespace std;

typedef int ElemType;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
//创建无头结点的单链表
ListNode* Create(void)
{
char s;
ListNode *tail = NULL;
ListNode *head = NULL;
while (1)
{

ListNode *tmp = new ListNode(0);     //定义一个s节点用来存放每次要输入的值
scanf("%d", &tmp->val);

if (head == NULL)
{
head = tmp;
}
else
{
tail->next = tmp;
}
tail = tmp;
s = getchar();
if (s == '\n') { break; }
}
if (tail != NULL)
tail->next = NULL;
return head;
}
//输出无头结点单链表
void List(ListNode *L)
{
ListNode *p;
p = L;  //
while (p != NULL)
{
printf("%2d", p->val);
p = p->next;
}
}
};

int main()
{
ListNode *L1;
int temp;
printf("请输入链表:\n");
L1 = Solution().Create();
printf("无头结点的链表为:\n");
Solution().List(L1);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: