欧美极品高清xxxxhd,国产日产欧美最新,无码AV国产东京热AV无码,国产精品人与动性XXX,国产传媒亚洲综合一区二区,四库影院永久国产精品,毛片免费免费高清视频,福利所导航夜趣136
標題:
C++語言 線性表的插入和刪除
[打印本頁]
作者:
daming
時間:
2014-12-30 01:28
標題:
C++語言 線性表的插入和刪除
本帖最后由 daming 于 2014-12-30 02:14 編輯
#include<iostream.h>
struct node
{
int data;
node *next;
};
//建立一條升序鏈表 (尾插法:最后建立的結點是表頭,故應降序輸入)
node *creat_sort()
{
node *p1,*head=NULL;
int a;
cout<<"建立一條有序鏈表,請輸入數據,以-1結束:\n";
cin>>a;
while(a!=-1){
p1=new node;
p1->data=a;
p1->next=head;
head=p1;
cin>>a;
}
return head;
}
//輸出鏈表上各個結點的值
void print(const node *head)
{
const node *p;
p=head;
cout<<"鏈表上各個結點的數據為:\n";
while(p!=NULL){
cout<<p->data<<'\t';
p=p->next;
}
cout<<endl;
}
//刪除鏈表上具有指定值的一個結點
node *delete_one_node(node *head,int num)
{
node *p1,*p2;
if(head==NULL){
cout<<"鏈表為空,無結點可刪!\n";
return NULL;
}
if(head->data==num){
p1=head;
head=head->next;
delete p1;
cout<<"刪除了一個結點!\n";
}
else{
p2=p1=head;
while(p2->data!=num&&p2->next!=NULL){
p1=p2;
p2=p2->next;
}
if(p2->data==num){
p1->next=p2->next;
delete p2;
cout<<"刪除了一個結點!\n";
}
else
cout<<num<<"鏈表上沒有找到要刪除的結點!\n";
}
return head;
}
//釋放鏈表的結點空間
void deletechain(node *h)
{
node *p1;
while(h){
p1=h;
h=h->next;
delete p1;
}
cout<<"已釋放鏈表的結點空間!\n";
}
//求鏈表的結點數
int count(node *head)
{
int n;
node *p;
p=head;
n=0;
while(p!=NULL){
n=n+1;
p=p->next;
}
return n;
}
////查找第k個結點
node *find(node *head,int k)
{
int i;
node *p;
i=1;
p=head;
while(i<k){
i++;
p=p->next;
}
return p;
}
//刪除鏈表上第K個結點
node *delete_k_node(node *head,int k)
{
int j=1;
node *p,*p1;
if(head==NULL){
cout<<"鏈表為空,無結點可刪!\n";
return NULL;
}
p=head;
if(k==1){
p=head;
head=head->next;
delete p;
cout<<"刪除了第一個結點!\n";
}
else{
p=find(head,k-1); //查找第k-1個結點,并由p指向該結點
if(p->next!=NULL){
p1=p->next;
p->next=p1->next;
delete p1;
cout<<"刪除了第"<<k<<"個結點!\n";
}
}
return head;
}
//插入一個結點,不改變鏈表上的升序關系
node *insert(node *head,int num)
{
node *p1,*p2,*p3;
p1=head;
p2=head->next;
while(!(((p1->data)<=num)&&((p2->data)>=num))){
p1=p1->next;
p2=p2->next;
}
p3=new node;
p3->data=num;
p1->next=p3;
p3->next=p2;
return head;
}
//測試函數
void main()
{
node *head;
int num;
head=creat_sort();
print(head);
cout<<"結點數:"<<count(head)<<endl;
cout<<"輸入要刪除結點上的序號!\n";
cin>>num;
head=delete_k_node(head,num);
print(head);
cout<<"輸入要刪除結點上的整數!\n";
cin>>num;
head=delete_one_node(head,num);
print(head);
cout<<"輸入要插入的整數!\n";
cin>>num;
head=insert(head,num);
print(head);
deletechain(head);
}
/**********************************************
建立一條有序鏈表,請輸入數據,以-1結束:
9 8 6 5 4 3 2 1 -1
鏈表上各個結點的數據為:
1 2 3 4 5 6 8 9
結點數:8
輸入要刪除結點上的序號!
1
刪除了第一個結點!
鏈表上各個結點的數據為:
2 3 4 5 6 8 9
輸入要刪除結點上的整數!
2
刪除了一個結點!
鏈表上各個結點的數據為:
3 4 5 6 8 9
輸入要插入的整數!
7
鏈表上各個結點的數據為:
3 4 5 6 7 8 9
已釋放鏈表的結點空間!
Press any key to continue
**************************************/
復制代碼
歡迎光臨 (http://www.raoushi.com/bbs/)
Powered by Discuz! X3.1