首页 > 学院 > 开发设计 > 正文

单循环链表的创建,搜索,遍历

2019-11-11 05:09:04
字体:
来源:转载
供稿:网友
#include<iostream>#include<stdlib.h>using namespace std;typedef struct _node{            int data;    struct _node *next;}Node;//链表节点结构。typedef struct{    Node *head;    Node *end;}List;void add(List *list,int d){    Node *p=(Node*)malloc(sizeof(Node));        p->data=d;    p->next=(list->head);//创建一个p指针,如果不需要循环链表p->next=NULL即可。        Node *last=list->head;//last指针作为遍历指针。    if(last)//判断边界,链表内是否有数据?    {        while((last->next)!=(list->head))        {            last=last->next;                    }        last->next=p;    }else{        list->head=p;        p->next=(list->head);    }        }void show(List *list){        if(list->head==NULL)    {        cout<<"nothing"<<endl;    }    else{                Node *p=(Node*)malloc(sizeof(Node));        p=list->head;        do{            cout<<p->data;            p=p->next;        }while(p!=(list->head));                    }    }void remove(List *list,int plc){        if(list->head==NULL)    {        cout<<"NULL";    }else{                Node *q=(Node*)malloc(sizeof(Node));                Node *p=(Node*)malloc(sizeof(Node));                p=list->head;        for(q=NULL;;q=p,p=p->next)            //这里判断条件为空,所以如果链表中没有寻找数据是不会跳出循环的,如果需要跳出循环条件为将代码参照show()里的遍历方式,或者判断q指针也是可以的。        {            if(p->data==plc)            {                                if(q)//防止链表中第一个节点为删除节点,此时需要判断q的值,因为你第一个节点前没有节点了。                {                    q->next=p->next;                                    }else{                    list->head=p->next;                }                                free(p);                break;            }                                }                    }    }int main(){            List list;    int n;    int m;    list.head=NULL;    cin>>n>>m;    for(int i=0;i<n;i++)    {        add(&list,i);            }    show(&list);    remove(&list,2);    cout<<endl;    show(&list);            return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表