Problem B: 子序列问题(线性表)

来源:互联网 发布:淘宝店铺会员管理 编辑:程序博客网 时间:2024/05/22 03:41

Problem B: 子序列问题(线性表)

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 300  Solved: 190
[Submit][Status][Web Board]

Description

两个整数序列A=a1,a2,a3,…,am和B=b1,b2,b3,…,bn已经存入两个单链表中,设计一个算法,判断序列B是否是序列A的子序列,代码给出如下,请修改~

本题只需提交修改部分

#include<stdio.h>
#include<malloc.h>
struct node             //定义结构体
{
    int data;
    struct node *next;
};
struct node *creat(int n)
{
    struct node *head,*p,*q; //head是头节点,p指向新开辟的节点,q指向已连接的上一个节点
    head=(struct node *)malloc(sizeof(struct node));//给head开辟一个节点
    q = head;  //q节点连接到head上
    while(n--)  //开辟n个新节点,逐个连到链表上
    {
        p=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);//p该连在q后边吧?
        q->next = p;
        q = p;

    }
    q->next = NULL;//链表结束
    return head;
}
void destroy(struct node *head)
{
 struct node *p;
 while(head!=NULL)
 {
  p=head->next;
  delete(head);
  head=p;
 }
}

int main()//建两条链表p,q
{
    int m,n,count=0;
    struct node *head1,*head2,*p,*q;
    scanf("%d",&m);
    head1 = creat(m);
    scanf("%d",&n);
    head2 = creat(n);
    q=head2->next;
    p = head1->next;
    while(q != NULL)  //双循环判断p是否是q的子列
    {
        while(p!=NULL)
        {
    /***修改代码******/
            if(q->data == p->data)
            {
                count++;
            }
            else
                p = p->next;
  /***********************/  
        }
        if(p != NULL)
            q = q->next;
        else
            break;
    }
    if(count == n)
        printf("yes\n");
    else
        printf("no\n");
    destroy(p);
    destroy(q);
    return 0;
}

Input

一个整数m,表示A序列的长度m。

m个数表示A序列中的m个数据元素。

一个整数n,表示B序列的长度n。

n个数表示B序列中的n个数据元素。

Output

yes 或者 no

Sample Input

912 13 14 15 6 71 18 19 10515 6 71 18 19

Sample Output

yes

HINT

代码实现:

#include<stdio.h>#include<malloc.h>struct node             //定义结构体{    int data;    struct node *next;};struct node *creat(int n){    struct node *head,*p,*q; //head是头节点,p指向新开辟的节点,q指向已连接的上一个节点    head=(struct node *)malloc(sizeof(struct node));//给head开辟一个节点    q = head;  //q节点连接到head上    while(n--)  //开辟n个新节点,逐个连到链表上    {        p=(struct node *)malloc(sizeof(struct node));        scanf("%d",&p->data);//p该连在q后边吧?        q->next = p;        q = p;     }    q->next = NULL;//链表结束    return head;}int main()//建两条链表p,q{    int m,n,count=0;    struct node *head1,*head2,*p,*q;    scanf("%d",&m);    head1 = creat(m);    scanf("%d",&n);    head2 = creat(n);    q=head2->next;    p = head1->next;    while(q != NULL)  //双循环判断p是否是q的子列    {        while(p!=NULL)        {               if(q->data == p->data)            {                count++;break;            }            else                p= p->next;        }        if(p != NULL)            q = q->next;        else            break;    }    if(count == n)        printf("yes\n");    else        printf("no\n");    return 0;}

0 0