笔试程序题专项----2012年408

本文介绍了一种使用链表进行数据存储的方法,并通过两个链表的交集查找演示了链表操作的具体实现。首先,通过加载字符串到链表中,然后打印链表的内容,接着将一个链表的尾部连接到另一个链表的特定节点,最后通过比较两个链表的长度并移动指针来找到它们的交集点。

 

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

typedef struct node
{
    char data;
    node *next;
} node,*pnode;

pnode head1,head2,p,q;

void print(pnode head)
{
    p=head->next;
    while(p!=NULL)
    {
        cout<<p->data<<" ";
        p=p->next;
    }
    cout<<endl;
}
pnode load1(pnode head,string str)
{
    pnode t=head,tt,res;
    for(int i=0; i<str.size(); i++)
    {
        tt=(pnode)malloc(sizeof(node));
        tt->data=str[i];
        tt->next=NULL;
        if(str[i]=='a') res=tt;
        t->next=tt;
        t=t->next;
    }
    return res;
}
pnode load2(pnode head,string str,pnode last)
{
    pnode t=head,tt,res;
    for(int i=0; i<str.length(); i++)
    {
        tt=(pnode)malloc(sizeof(node));
        tt->data=str[i];
        tt->next=NULL;
        t->next=tt;
        t=t->next;
    }
    tt->next=last;
    return res;
}

int len(pnode head)
{
    pnode t=head->next;
    int sum=0;
    while(t->next!=NULL)
    {
        sum++;
        t=t->next;
    }
    return sum;
}
int main() {

    head1=(pnode)malloc(sizeof(node));
    head1->next=NULL;
    head2=(pnode)malloc(sizeof(node));
    head2->next=NULL;

    pnode temp=load1(head1,"downloading");
    print(head1);
    load2(head2,"re",temp);
    print(head2);

    int l1=len(head1);
    int l2=len(head2);
    pnode p1=head1->next;
    pnode p2=head2->next;

    if(l1>l2)
    {
        for(int i=0; i<l1-l2; i++)
            p1=p1->next;
    }
    else
    {
        for(int i=0; i<l2-l1; i++)
            p2=p2->next;
    }


    while((p1!=NULL)&& p1!=p2)
    {
        p1=p1->next;
        p2=p2->next;
    }
    cout<<p1->data<<endl;
    return 0;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值