数据结构——单链表的基本操作

#include <iostream>
using namespace std;

struct node
{
int data;
struct node * next;
};
typedef
struct node Node;
//创建链表函数
Node *Creat()
{
Node
*h=NULL,*p1,*p2;
cout
<<"Input integer to create a list,0 to end:"<<endl;
p1
=(Node *) malloc(sizeof(Node)); //给第一个节点分配内存
cout<<"请输入第一个数"<<endl;
cin
>>p1->data;
if(p1->data!=0)
h
=p1;
while(p1->data!=0) //以0结束输入
{
p2
=p1;
p1
=(Node *) malloc(sizeof(Node));
cin
>>p1->data;
p2
->next=p1;
}
if(h!=NULL)
p2
->next=NULL; //h==NULL时链表是空的,p2还没有指向任何对象,故不存在next域
return h;
}
//end creat
//打印输出函数
void PrintList(Node *h)
{
if(h==NULL)
cout
<<"List is empty!"<<endl;
else
{
while(h!=NULL)
{
cout
<<h->data<<" ";
h
=h->next;
}
cout
<<"NULL"<<endl;
}
}
//end printlist
//插入函数
Node * insert(Node *h,int value)
{
Node
*previous,*current,*newp;
previous
=NULL;
current
=h;
while(current!=NULL && current->data<value)
{
previous
=current;
current
=current->next;
}
newp
=(Node *)malloc(sizeof(Node));
newp
->data=value;
newp
->next=current;

if(previous==NULL) //插在表头,当链表是空时,或者第一个元素就大于要插入的元素时。
{
h
=newp;
}
else
previous
->next=newp;

return h;
}
//end insert
//删除元素函数
Node * delet(Node *h, int value)
{
Node
*previous,*current;
Node
*temp; //临时保存要删除的节点,然后指针重新连接后再释放该节点的内存
if(value==h->data) //删除头结点
{
temp
=h;
h
=h->next;
free(temp);
}
else
{
previous
=h;
current
=h->next;
while(current!=NULL && current->data!=value)
{
previous
=current;
current
=current->next;
}
if(current!=NULL)
{
temp
=current;
previous
->next=current->next;
free(temp);
}
else
cout
<<"node is not found!"<<endl;
}
return h;
}
//end delet()

//冒泡排序链表
Node * bubblesort(Node *head)
{
Node
*p1, *p2; //用于排序
Node *lastExchangePtr; //冒泡排序法的主线
//遍历链表,使得p1指向链表的最后一个结点,从而为下面冒泡法的循环做准备
for(p1=head; p1->next!=NULL; p1=p1->next);
for(; p1!=head; p1=lastExchangePtr) //p1向前递减
{
lastExchangePtr
= head; //防止内循环没有执行以致lastExchangePtr没有改变从而导致死循环
for(p2=head; p2!=p1; p2=p2->next)
{
if(p2->data > p2->next->data)
{
swap(p2
->data, p2->next->data); //结点本身的位置并不交换,而只交换两个结点之间的数据,从而使问题得到了简化
lastExchangePtr = p2;
}
}
}
return head;
}
//end bubblesort

int main()
{
Node
*head1;

//创建链表
head1=Creat(); //head1接受返回的指向头结点指针
//输出链表
PrintList(head1); //将表头指针传给打印函数

//排序链表
cout<<"单链表排序"<<endl;
bubblesort(head1);
//输出链表
PrintList(head1);

//插入节点,注意可能是空表
cout<<endl<<"请输入要插入的数字"<<endl;
int i;
cin
>>i;
Node
*head2;
head2
=head1;
while(i!=0)
{
head2
=insert(head2,i);
cin
>>i;
}
//输出链表
PrintList(head2); //注意这应该是head2

//删除元素
cout<<endl<<"请输入要删除的元素"<<endl;
cin
>>i;
while(i!=0)
{
head2
=delet(head2,i);
//输出链表
PrintList(head2);
cin
>>i;
}

return 0;
}

 

posted @ 2010-07-21 00:49  忧国忧铭  Views(1173)  Comments(0)    收藏  举报