站点图标 陌路寒暄

建立链表(线性表)

建立链表(线性表)

时间: 1ms        内存:128M

描述:

(线性表)设键盘输入n个英语单词,输入格式为n, w1, w2, …,wn,其中n表示随后输入英语单词个数,试编一程序,建立一个单向链表,实现:如果单词重复出现,则只在链表上保留一个。

输入:

4

now come now please 

输出:

now come please

示例输入:

3
go come keep

示例输出:

go come keep 

提示:

参考答案(内存最优[0]):

#include<iostream>
#include<string.h>
using namespace std;
struct stu
{
    string word;
    stu *next;
};
int main()
{
    stu *head,*p1,*p2;
    stu *a;
    int n,m=0;
    cin>>n;n=n-1;
    p1=new stu;
    cin>>p1->word;
    p2=p1;
    head=p1;p1->next=NULL;
    while(n)
    {
        p1=new stu;
        cin>>p1->word;
        a=head;
        do
        {
            if(p1->word==a->word)
                m=1;
            a=a->next;
        }while(a!=NULL);
        if(m!=1)
        {
            p2->next=p1;
            p2=p1;p2->next=NULL;
        }
        n--;m=0;
    }
    p2->next=NULL;
    stu *p;
    p=head;
    do
    {
        cout<<p->word<<" ";
        p=p->next;
    }while(p!=NULL);
    return 0;
}

参考答案(时间最优[0]):

#include <iostream>
#include<string>
using namespace std;
struct linklist
{
    string num;
    linklist *next;
};
linklist *creat()
{
    linklist *head,*p1,*p2;
    int m,n;
    cin>>m;
    for(n=1;n<=m;n++)
    {
        p1=new linklist;
        cin>>p1->num;
        if(n==1) head=p1,p2=p1;
        else p2->next=p1,p2=p1;
    }
    p2->next=NULL;
    return head;
}

void print_build_link(linklist *head)
{
    linklist *p1,*p2,*p3,*p4;
    int n,m;
	p1=head;
	m=0;
    while(p1!=NULL)
    {
		m++;
		n=0;p2=head;
		while(p2!=NULL)
		{
			n++;
			if(p2->num==p1->num) break;
			p2=p2->next;
		}
		if(m==n)
		{
        cout<<p1->num<<" ";
		}
        p1=p1->next;
    }
	while(head!=NULL)
	{
		p1=head;
		head=head->next;
		delete p1;
	}
}
int main()
{
    linklist *p;

  p=creat();
    print_build_link(p);
    return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

退出移动版