/这里是链表的创建其包含的是头指针phead,头节点,以及尾节点p->next = NULL 为链表创建结束标志。
/判断指针为空十分重要,当然也不能忘了释放,代码是:
if(head !=NULL){
free(head);
head = NULL;
}
head = (SLNode*)malloc(sizeof(SLNode));
head->data=x;
if(head !=NULL){
r = head;
cout<<"空间成功申请!"<<endl;
/创建一个指针*p,*s来实现创建,代码是:
p = (SLNode*)malloc(sizeof(SLNode));
p->data = x;
r->next = p;
r = p;
/判断是否继续执行创建,输入新的数据(这里写的不好,仅供参考),代码是:
cout<<"是否继续输入:Y/N"<<endl;
cin>>c;
if(c == 'Y'||c == 'y'){
continue;
}else{
r->next= NULL;
}
//先建立一个完整的链表,然后对其进行增删改查
//在这里我们采用尾插入的方式来对其进行建立链表
#include <iostream>
using namespace std;
typedef int DataType;
//声明节点
typedef struct node{
DataType data;
struct node *next;
}SLNode;
//创建头指针
SLNode *InitiateHead(SLNode*phead){
phead = (SLNode*)malloc(sizeof(SLNode));
phead->next = NULL;
return phead;
}
SLNode * Create_List(SLNode *head){//头节点开始的申请空间
SLNode *r,*p;
int x;
char c ;
if(head !=NULL){
free(head);
head = NULL;
}
head = (SLNode*)malloc(sizeof(SLNode));
head->data=x;
if(head !=NULL){
r = head;
cout<<"空间成功申请!"<<endl;
}
cout<<"创建链表:"<<endl;
while(c !=NULL||c!='n'){
cout<<"请输入:";cin>>x;
p = (SLNode*)malloc(sizeof(SLNode));
p->data = x;
r->next = p;
r = p;
cout<<"是否继续输入:Y/N"<<endl;
cin>>c;
if(c == 'Y'||c == 'y'){
continue;
}else{
r->next= NULL;
cout<<"首地址1:"<<head<<endl;///
cout<<"链表创建完成!"<<endl;
return head;
}
}
}
void OutPut_List(SLNode *phead){
SLNode *p;
// cout<<"首地址3:"<<phead<<endl;///
//cout<<"首地址4:"<<phead->next<<endl;
p = phead->next->next;
//cout<<"data:"<<p->data<<endl;
int i = 1;
while(p!=NULL){
cout<<"第"<<i<<"一个元素:"<<p->data<<endl;
i++;
p = p->next;
}
}
void menu(){
cout<<"_________________________________________________________"<<endl;
cout<<"|*******************************************************|"<<endl;
cout<<"|*****************欢迎进入菜单选项*.********************|"<<endl;
cout<<"|*****************进入初始化阶段请稍后....**************|"<<endl;
cout<<"|*****************1、创建链表 ***************|"<<endl;
cout<<"|*****************2、输出链表 *****************|"<<endl;
cout<<"|*******************************************************|"<<endl;
cout<<"_________________________________________________________"<<endl;
}
void operation(SLNode *phead){
SLNode *p,*p1;
int input;
cout<<"请选择:"<<endl;
cin>>input;
//p1=InitiateHead(phead);//头指针
switch(input){
case 1:p1=Create_List(p);/* cout<<"首地址2:"<<p1<<endl;*/ phead->next=p1; phead->next=p1;menu();operation(phead); break;
case 2:cout<<"输出已创建好的链表中的数据:"<<endl;OutPut_List(phead);menu();operation(phead);break;
}
}
int main(){
SLNode *phead;
phead=InitiateHead(phead);
cout<<"首地址2.1:"<<phead<<endl;
menu();
operation(phead);
return 0;
}