链表指针

来源:互联网 发布:网络出版物 编辑:程序博客网 时间:2024/05/16 06:52

前言:学习链表的基础是你要对动态分配内存结构体指针有所了解。

一、什么是链表?

链表就是一种动态分配内存的数据结构。

二、链表的作用或者说好处。

1.链表可以有效的节省内存。

三、链表的基本操作

1.定义:

链表的定义是基于结构体的,其中一部分用来存储数据,另一部分用来存储下一个结点的地址。

2.建立:

就自己理解而言,链表的建立等同于头结点的建立。需要说明的是根结点不存储数据,只存储下一个结点的地址。

3.添加:

链表的添加,就是添加一个结点。我们要做的就是:第一,新申请一片内存。第二,对新申请的结点的数据和指针进行处理。需要注意的是我们每申请一个结点都是当前的最后一个结点。

4.查找:

结点的查找需要从根节点开始寻找,这就的保存根节点的需要。

5.

结点的删除就是将该结点的地址删除。

四、结束语

链表是一些重要的数据结构的基础,需要熟练的掌握。

练习Nyoj 移动的小球

双向循环链表

写的单向链表不知道怎么回事调试不出来。

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;struct Node{    int date;    Node *front,*next;};int n,m;Node *root;void Build(){    Node *frontnode,*tmp;    root=(Node*)malloc(sizeof(Node));    root->date=1;    frontnode=root;frontnode->next=NULL;    for(int i=2;i<=n;i++){        tmp=(Node*)malloc(sizeof(Node));        tmp->date=i;//date        tmp->front=frontnode;//index        frontnode->next=tmp;        tmp->next=NULL;        frontnode=tmp;    }    tmp->next=root;root->front=tmp;}//如果删除的是root,改变一下root就可以了.Node* find(int x){    Node *p=root;    while(1){        if(p->date==x) return p;        p=p->next;    }}int main(){//    freopen("Input.txt","r",stdin);    int T;    scanf("%d",&T);    while(T--){        scanf("%d%d",&n,&m);getchar();        Build();        char c;int a,b;        for(int i=1;i<=m;i++){            scanf("%c%d%d",&c,&a,&b);getchar();            if(c=='A'){                Node *tmp1=find(a),*tmp2=find(b);                tmp1->front->next=tmp1->next;tmp1->next->front=tmp1->front;//delete                tmp1->next=tmp2;tmp1->front=tmp2->front;//insertnode                tmp2->front->next=tmp1;tmp2->front=tmp1;//'left,right            }            else if(c=='B'){                Node *tmp1=find(a),*tmp2=find(b);                tmp1->front->next=tmp1->next;tmp1->next->front=tmp1->front;//delete                tmp1->front=tmp2;tmp1->next=tmp2->next;                tmp2->next->front=tmp1;tmp2->next=tmp1;            }            else {                Node *tmp1=find(b);                if(a==1) printf("%d\n",tmp1->next->date);                else printf("%d\n",tmp1->front->date);            }        }    }    return 0;}


0 0