Last semester I didn’t grasp the idea of linked list.Here is a review about the basic manipulation of the linked list

#include<iostream>
#include<string>
using namespace std;
int n;
struct num
{
    int data;
    struct num *next;
};
struct num *create()//create a new linked list
{
    struct num *head=new num,*tail;//open  new space for head
    cout<<"Please input the size of linked list"<<endl;
    cin>>n;
    cout<<"Please input the element of linked list"<<endl;
    cin>>head->data;
    head->next=NULL;
    tail=head;
    for(int i=1;i<n;i++)
    {
        tail->next=new num;
        cin>>tail->next->data;
        tail->next->next=NULL;//ensure that when encountered with the end of the problem ,tail->next==NULL
        tail=tail->next;
    }
    return head;
}

void output(num *start)//output a list from begin to end.
{
    num *move=start;
    while(move)
    {
        cout<<move->data<<' ';
        move=move->next;
    }
    cout<<endl;
}

num *del(num *start,int x )//delete an element ‘x’ from list.
{
    num *ahead,*now=start;
    while(true)
        {
        if(now->data==x)
        {
            if(now==start)
                now=now->next;
            else
                {
                ahead->next=now->next;
                }
            cout<<"The element "<<x<<" is deleted"<<endl;
            delete now ;
            break;
        }
        if(now->next==NULL)
        {
            now =NULL;
            cout<<"no such element"<<endl;
            break;
        }
        ahead=now;
        now=now->next;
        }
    return start;
}
num *insert(num *head,num *newnode)//insert an new element,which is what  newnode points to.newnode->data=element.
{
num *move=head;
if(newnode->data<head->data)
    {
        newnode->next=head;
        head=newnode;
        return head;
    }
while(move->next!=NULL)
{
    if(newnode->data<move->next->data)
    {
        newnode->next=move->next;
        move->next=newnode;//如果把这两句颠倒会有很严重的问题!仔细思考
        return head;

    }
    move=move->next;
}
newnode->next=move->next;
move->next=newnode;
return head;
}
int main()
{

    num *p=create();

int x;
cout<<"Please input an element which is to be deleted"<<endl;
cin>>x;

    num *q=del(p,x);
    output(q);
    cout<<"Please input an number which is to be added at sequenial order"<<endl;
num *nnode=new num;
cin>>nnode->data;
num *l=insert(p,nnode);
output(l);
    return 0;
}

posted on 2010-04-06 12:59  梦涵  阅读(117)  评论(0编辑  收藏  举报