有关链表的认知

本文深入探讨了双向链表的基本原理,特别关注于head指针的作用及其对节点数据的影响。通过实例代码演示了如何创建双向链表、查找特定节点及其前驱后继节点的方法,并提供了关键代码片段的解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直到今天才发现 head指针并不为空,head->data值默认为0;  WA七遍的教训

若是建立双向链表,则第一个元素的向前指的指针p->pre并不能指向tail,而是要指向NULL;

可根据以下程序来进行判断

if(!head)
        printf("head is NULL\n");
    else printf("head isn't NULL\n");
    printf("head->data is %d\n",head->data);

e.g.:

输入m,n,分别代表代表节点个数,要找的关键字的个数

输入m个数;

输入n个关键字;

输出此关键字的前驱节点关键字和后继节点关键字。如果给定的关键字没有前驱或者后继,则不输出。给定关键字为每个输出占一行.


#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
    int data;
    struct node *next,*pre;
} node;

void creat(node *&head,int n)
{
    node *p,*tail;
    head=new node;
    head->next=NULL;
    tail=head;
    if(!head)
        printf("head is NULL\n");
    else printf("head isn't NULL\n");
    printf("head->data is %d\n",head->data);
    int i;
    for(i=0; i<n; i++)
    {
        p=new node;
        p->next=NULL;
        scanf("%d",&p->data);
        tail->next=p;
        if(i==0)
       p->pre=NULL;
        else p->pre=tail;
        tail=p;
    }
}

void finds(node *head,int t,int &pres,int &last,int &flag1,int &flag2)
{
    node *p;
    p=head->next;
    while(p)
    {
        if(p->data==t)
        {
            if(p->pre)
            {
                flag1=1;
                pres=p->pre->data;
            }
            if(p->next)
            {
                flag2=1;
                last=p->next->data;
            }
            break;
        }
        p=p->next;
    }

}

int main()
{
    node *head;
    int n,m,t;
    scanf("%d%d",&n,&m);
    creat(head,n);
    while(m--)
    {
        scanf("%d",&t);
        int pres=-1;
        int last=-1;
        int flag1=0,flag2=0;
        finds(head,t,pres,last,flag1,flag2);
        if(!flag1&&flag2)
            printf("%d\n",last);
        else if(flag1&&!flag2)
            printf("%d\n",pres);
        else if(flag1&&flag2)
            printf("%d %d\n",pres,last);
    }
    return 0;
}


运行结果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值