【算法笔记第7.3节 】问题 D: 链表查找(线性表)

[提交][状态][讨论版][命题人:外部导入]

题目描述

 线性表(a1,a2,a3,…,an)中元素递增有序且按顺序存储于计算机内。要求设计一算法完成:

(1) 用最少时间在表中查找数值为x的元素。

(2) 若找到将其与后继元素位置相交换。

(3) 若找不到将其插入表中并使表中元素仍递增有序。

输入

输入:x=3

输入长度:9

输入数据:2 3 5 7 12 15 17 23 45

输出

相同元素为:3

交换后的链表为:2 5 3 7 12 15 17 23 45

样例输入

4
9
2 3 5 7 12 15 17 23 45

样例输出

no
2 3 4 5 7 12 15 17 23 45 

在deal函数中,不能先判断now->next!==NULL,因为此时now可能为null,再访问其next,会导致程序错误。

#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>

using namespace std;
struct node
{
   int data;
   node *next;
};
void deal(node *&head, int x)
{
    node *now = head->next;
    while(now != NULL)
    {
        if(now->data==x)
        {
            printf("yes\n");
            break;
        }
        else
            now = now -> next;
    }
   // printf("%d\n",now->data);
    if(now==NULL)//此处和else if判断顺序不能改变
    {
        node *p = head;
        while(p->next->data < x)
        {
            p = p->next;
        }
        node *a;
        a = new node;
        a->data = x;
        a->next = p->next;
        p->next = a;
        printf("no\n");
    }
    else if(now->next!=NULL)
    {
        int temp;
        temp = now->data;
        now->data = now->next->data;
        now->next->data = temp;
    }
    node *b = head->next;
    while(b!=NULL)
    {
        printf("%d", b->data);
        if(b->next!=NULL)
            printf(" ");
        else
            printf("\n");
        b = b->next;
    }
}

int main()
{
    int x;
    while(scanf("%d",&x)!=EOF)
    {
        int n;
        scanf("%d",&n);
        node *head, *now, *p;
        head = new node;
        head->next = NULL;
        p = head;
        int t;
        for(int i=0; i<n; i++)
        {
            scanf("%d",&t);
            now = new node;
            now->data = t;
            now->next = NULL;
            p->next = now;
            p = now;
        }
            deal(head, x);
        }


    return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值