#include <iostream>
using namespace std;
typedef struct LinkNode{
int data;
struct LinkNode *next;
}LNode,*LinkedList;
void HeadInsert(LNode* &head)
{
int x;
head=(LNode *) malloc(sizeof (LNode));
head->next=NULL;
cin>>x;
while(x!=9999){
LNode* node=(LNode *) malloc(sizeof (LNode));
node->data=x;
node->next=head->next;
head->next=node;
cin>>x;
}
}
void TailInsert(LNode* &head){
cout<<"开始创建单链表……"<<endl;
int x;
head=(LNode *) malloc(sizeof (LNode));
head->next=NULL;
LNode *tail=head;
cin>>x;
while(x!=-1){
LNode* node=(LNode *) malloc(sizeof (LNode));
node->data=x;
node->next=NULL;
tail->next=node;
tail=node;
cin>>x;
}
}
LNode* getElemByOrder(LNode *head,int position){
LNode *p=head->next;int i=1;
if(position<1)return NULL;
while(p!=NULL){
if(position==i)
return p;
else {
p=p->next;++i;
}
}
return NULL;
}
LNode* LocateElem(LNode* head,int value){
LNode *p=head->next;
while(p!=NULL){
if(p->data==value)return p;
p=p->next;
}
return NULL;
}
int getLength(LNode* head){
int num=0;
LNode *p=head;
while(p->next!=NULL){
++num;
p=p->next;
}
return num;
}
bool BehindInsert(LNode *head,int position){
if(position>getLength(head)+1||position<1)return false;
LNode *s=(LNode*) malloc(sizeof (LNode));
int data;
cout<<"请输入插入结点的值:";cin>>data;
s->data=data;
LNode *p= getElemByOrder(head,position-1);
s->next=p->next;
p->next=s;
return true;
}
bool DeleteNode(LNode* head,int position){
if(position>getLength(head)+1||position<1)return false;
LNode *p= getElemByOrder(head,position-1);
LNode *q=p->next;
p->next=q->next;
free(q);
}
void print(LNode *list){
LNode *p=list;
while(p->next!=NULL){
p=p->next;
cout<<p->data<<" ";
}
cout<<endl;
}
int main (){
LNode *list,*list2;int position;int value;
TailInsert(list2);
cout<<"链表创建成功:";
print(list2);
cout<<"请输入要插入结点的位置:";cin>>position;
BehindInsert(list2,position);
print(list2);
cout<<"请输入要删除结点的位置:";cin>>position;
DeleteNode(list2,position);
print(list2);
return 0;
};
|