数据结构顺序表(2)(链表)

来源:互联网 发布:一年php工资7千 编辑:程序博客网 时间:2024/06/01 20:04
/*在长度为n(n<1000)的顺序表中可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺
序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只能有一个)。 */

#include<iostream>
#include<stdlib.h>
using namespace std;

struct node
{
    struct node *next;
    int data;
};
int main()
{
    int n,a;
    //顺序建立链表
    struct node *head,*tail,*p,*q,*s;//head是头结点,保存链表位置
    head=(struct node *)malloc(sizeof (struct node ));//将申请的空间的地址强制转化为 struct node * 指针类型然后赋值给head。
    head->next=NULL;
    tail=head;
    cin>>n;
    int i;
    int k=0;
    for(i=0;i<n;i++)//输入n后创建n长度的链表
    {
        p=(struct node *)malloc(sizeof(struct node ));
        cin>>a;
        p->data=a;
        p->next=NULL;
        tail->next=p;
        tail=p;
    }

    p=head->next;//p等于头结点下一个的地址
    while(p)
    {
        q=p;
        while(q->next)
        {
            if(q->next->data!=p->data)
            {
                q=q->next;
            }
            else
            {
                k++;
                s=q->next;
                q->next=s->next;
                free(s);
            }
        }
        p=p->next;
    }
    cout<<n-k<<" "<<endl;
    p=head->next;
    while(p!=NULL)
    {
      if(p->next==NULL)
      {
          cout<<p->data<<endl;
      }
        else
            cout<<p->data<<" ";
        p=p->next;
    }
    return 0;
}

原创粉丝点击