输入a,b,c,d,e,f六个字符作为结点的数据,创建具有六个数据元素的链表,然后实现输出链表结点中的数据元素值。要求有交互界面,输入1为创建链表,输入0为退出程序,输入2为显示链表中的数据元素
代码如下:
#include <iostream>
using namespace std;
typedef struct Node
{
char c;
struct Node* next;
};
//创建链表
struct Node* createList()
{
int i,n;
char ch;
struct Node* head,*p,*t;
head = new Node;
head->next = NULL;
p = head;
n = 6;
cout << "请输入6个字符:";
for (i=0;i<n;i++)
{
t = new Node;
cin >> t->c ;
t->next = NULL;
p->next = t;
p = t;
}
return head;
}
//显示链表
void printList(struct Node* head)
{
struct Node* p;
if(head == NULL) return;
p = head->next;
while(p)
{
cout << p->c << endl;
p = p->next;
}
}
int main()
{
int opt;
char ch;
struct Node* head = 0;
while(1)
{
cout << "1.创建链表"<<endl;
cout << "2.显示链表"<<endl;
cout << "0.退出"<<endl;
cin >> opt;
switch(opt)
{
case 1:
head = createList();
cout << "链表创建成功"<< endl;
break;
case 2:
if(head == 0)
cout <<"链表为空"<<endl;
else
printList(head);
break;
case 0:
return 0;
}
}
return 0;
}