#include <iostream>
#include<stdlib.h>
#include <iomanip>
using namespace std;
struct node//1、定义链表
{
int num;
node *next;
};
void Makelist(node*&head) //2、创建链表
{
node *p=NULL, *s;
s = new node;
cin >> s->num;
while (0!= s->num)
{
if (head == NULL)
{
head = s;
}
else
{
p->next=s;
}
p = s;
s = new node;
cin >> s->num;
}
p->next = NULL;
delete s;
};
void chatouwei(node*&head) //3、头前插进新节点和尾后插进新节点
{
//头前插进
node *t = NULL, *p, *temp;//临时储存;
t = new node;
cout << "请输入你的头前新节点值!" << endl;
cin >> t->num;
t->next = head;
head = t;
//尾后插进
cout << "请输入你的尾后新节点值!" << endl;
t = new node;
cin >> t->num;
temp = t;
p = head;
while (p->next!=NULL)
{
p = p->next;
}
p->next = temp;
temp->next = NULL;
t = new node;//解:如果新建delete s的话相当delete t导致链表连不上
delete t;
}
void chapqianxin(node*&head) //4、在某个节点前面插入新节点;
{
node *p = NULL, *q = NULL, *s=NULL, *w=NULL; int n;;
cout << "请选择你的节点值" << endl;
cin >> n;
for (p = head, q = p->next; q;p=q,q=q->next)
{
if (head->num==n)//判断头节点
{
cout << "请输入你的新节点值" << endl;
s = new node;
cin >> s->num;
s->next = head;
head = s;
break;
}
if (q->num == n)//判断下一节点
{
cout << "请输入你的新节点值" << endl;
s = new node;
cin >> s->num;
w = s;
p->next = w;
w->next = q;
s = new node;//解:如果新建delete s的话相当delete w导致链表连不上
delete s;
break;
}
}
}
void chaphouxin(node*&head) //5、在某个节点p后面插入新节点;
{
node *p = NULL, *s = NULL, *w; int n;;
p = head;
cout << "请选择你的节点值" << endl;
cin >> n;
while (p)
{
if (p->num==n)
{
cout << "请输入你的新节点值" << endl;
s = new node;
cin >> s->num;
w = s;
w->next = p->next;
p->next = w;
s = new node;
break;
}
p = p->next;
}
delete s;
}
void deletehead(node*&head) //6编写删除头节点方法
{
node *h = head;
head = head->next;
delete h;
}
void deletenode(node*&head) //7、删除某个节点
{
node *p=NULL,*q;
int n;
cout << endl;
cout << "请输入你的节点值" << endl;
cin >> n;
for (p = head, q = p->next; q;p=q,q=q->next)
{
if (p->num==n)
{
node *h = head;
head=head->next;
delete h;
break;
}
if (q->num==n)
{
p->next = q->next;
delete q;
break;
}
}
};
void showlist(node*&head) //8、输出链表
{
node *h = head;
while (h)
{
cout << h->num << ends;
h=h->next;
}
};
void main()
{
node *head = NULL;
Makelist(head);//创建链表
chatouwei(head);//头前插进新节点和尾后插进新节点
chapqianxin(head);//在某个节点前面插入新节点;
chaphouxin(head);//在某个节点p后面插入新节点;
deletehead(head);//编写删除头节点方法
deletenode(head);//删除某个节点
showlist(head);//输出链表
}
这一切廓然开朗,这一切原来如此,舒服,加油!!!