資料結構實驗之連結串列七:單連結串列中重複元素的刪除

HowieLee59發表於2019-03-11

Problem Description

按照資料輸入的相反順序(逆位序)建立一個單連結串列,並將單連結串列中重複的元素刪除(值相同的元素只保留最後輸入的一個)。

Input

第一行輸入元素個數 n (1 <= n <= 15);
第二行輸入 n 個整數,保證在 int 範圍內。

Output

第一行輸出初始連結串列元素個數;
第二行輸出按照逆位序所建立的初始連結串列;
第三行輸出刪除重複元素後的單連結串列元素個數;
第四行輸出刪除重複元素後的單連結串列。

Sample Input

10
21 30 14 55 32 63 11 30 55 30

Sample Output

10
30 55 30 11 63 32 55 14 30 21
7
30 55 11 63 32 14 21

Hint

Source

不得使用陣列!

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

typedef struct Node{
    int data;
    struct Node *next;
}node;

void create(node * &head,int m){
    node *p;
    head = new Node;
    head->next = NULL;
    for(int i = 0 ; i < m ; i++){
        p = new Node;
        scanf("%d",&p->data);
        p->next = NULL;
        p->next = head->next;
        head->next = p;
    }
    printf("%d\n",m);
}

void del(node * &head,int m){
    int f = 0;
    node *p,*q,*t;
    t = head->next;
    while(t){
        p = t;
        q = t->next;
        while(q){
            if(t->data == q->data){
                f++;
                p->next = q->next;
                free(q);
                q = p->next;
            }else{
                p = q;
                q = q->next;
            }
        }
        t = t->next;
    }
    printf("%d\n",m-f);
}

void print(node * &head){
    node *p;
    p = head->next;
    while(p){
        if(p->next == NULL){
            printf("%d\n",p->data);
        }else{
            printf("%d ",p->data);
        }
        p = p->next;
    }
}

int main(){
    node *head;
    int n;
    scanf("%d",&n);
    create(head,n);
    print(head);
    del(head,n);
    print(head);
    return 0;
}

 

相關文章