linklist2

/******链表检索、插入、删除、交换**************/
#include<iostream>
using namespace std;
typedef struct _LinkedList
{
    int data;
    struct _LinkedList *nextnode;
}LinkedList;

int main()
{
    struct _LinkedList *newnode=NULL;
    struct _LinkedList *temp=NULL;
    struct _LinkedList *head=NULL;

    int i=0;
    for(i=0;i<=9;i++)
    {
        newnode=(LinkedList*)malloc(sizeof(LinkedList));
        newnode->data=i;
        newnode->nextnode=NULL;

        if(i==0)
        {
            head=newnode;
            temp=newnode;
        }
        else{
            temp->nextnode=newnode;
            temp=newnode;
        }
    }
//检索 以下
    int key0;
    cout<<"要查找什么"<<endl;
    cin>>key0;
    struct _LinkedList *p=NULL;
    struct _LinkedList *p0=NULL;
    p=head;
    while(p!=NULL && p->data!=key0)
    {
        p0=p;
        p=p->nextnode;
    }

    if(p==NULL)
    cout<<"not found"<<endl;
    else cout<<"p->data="<<p->data<<endl;
/***要查找什么
5
p->data=5
****/

//插入100插在2和3之间

    p=head;
    while(p->data!=3)//使p指向3;  100插在2和3之间
    {
        p0=p;
        p=p->nextnode;
    }

    newnode=(LinkedList*) malloc (sizeof(LinkedList));
    newnode->data=100;
    newnode->nextnode=p;
    p0->nextnode=newnode;
    p0=newnode;

    temp=head;
    while(temp!=NULL)
    {
        cout<<temp->data<<"->";
        temp=temp->nextnode;
    }
    cout<<endl;
    /**   0->1->2->100->3->4->5->6->7->8->9->   ***/

//删除掉100;//构造辅助指针q
    p=head;
    while(p->data!=100)
    {
        p0=p;
        p=p->nextnode;
    }


    struct _LinkedList *q=NULL;
    struct _LinkedList *q0=NULL;
    struct _LinkedList *g=NULL;
    struct _LinkedList *y=NULL;
    struct _LinkedList *y0=NULL;
    q=p;
    p=p->nextnode;
    p0->nextnode=p;
    free(q);

    temp=head;
    while(temp!=NULL)
    {
        cout<<temp->data<<"->";
        temp=temp->nextnode;
    }
    cout<<endl;

//0->1->2->3->4->5->6->7->8->9->

    //交换 2 5

    //p指向2
    p=head;
    while(p->data!=2)
    {
        p0=p;
        p=p->nextnode;
    }

    //q指向5
    y=head;
    while(y->data!=5)
    {
        y0=y;
        y=y->nextnode;
    }

    //交换p->nextnode q->nextnode
    g=p->nextnode;
    p->nextnode=y->nextnode;
    y->nextnode=g;

    //交换p0->nextnode p1->nextnode
    p0->nextnode=y;
    y0->nextnode=p;

    //下面交换p q所指的为链表前段的5
    p=p0->nextnode;
    y=y0->nextnode;

    temp=head;
    while(temp!=NULL)
    {
        cout<<temp->data<<"->";
        temp=temp->nextnode;
    }
    cout<<endl;
//0->1->5->3->4->2->6->7->8->9->


    LinkedList* temp2;
    temp = head;
    while( temp != NULL ){
        temp2 = temp->nextnode;
        free(temp);
        temp = temp2;
    }























}

猜你喜欢

转载自www.cnblogs.com/luojialing/p/10338431.html