1. 程式人生 > >資料結構實驗之連結串列七:單鏈表中重複元素的刪除(SDUT 2122)

資料結構實驗之連結串列七:單鏈表中重複元素的刪除(SDUT 2122)

#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
    int data;
    struct node* next;
} Node;
Node* Createlist(int n)
{
    Node* head,*p;
    int i,d;
    head=(Node *)malloc(sizeof(Node));
    head->next=NULL;
    for(i=1; i<=n; i++)
    {
        p=(Node*)malloc(sizeof(Node));
        scanf("%d",&d);
        p -> data = d;
        p -> next = head -> next;
        head -> next = p;
    }
    return head;
};
int main()
{
    Node* head,*p,*t,*q;  
    int n;
    scanf("%d",&n);
    head = Createlist(n); 
    q = head -> next;  
    printf("%d\n",n);
    for(p = head -> next; p !=NULL ; p = p->next) 
        if(p == head -> next)
            printf("%d", p -> data);
        else
            printf(" %d",p -> data);
    printf("\n");
    while(q)
    {
        t = q;  
        p = q -> next;
        while(p)
        {
            if(q -> data == p -> data) 
            {
                t -> next = p -> next;
                n --;
                p = p -> next;
            }
            else
            {
                t = t -> next;
                p = p -> next;
            }
        }
        q = q -> next;
    }
    printf("%d\n",n);
    for(p = head -> next; p != NULL; p = p -> next)
    {
        if(p == head -> next)
            printf("%d",p -> data);
        else
            printf(" %d",p -> data);
    }
    return 0;
}