1. 程式人生 > >Deduplication on a Linked List(兩個測試點)

Deduplication on a Linked List(兩個測試點)

#include <stdio.h>

#include <stdlib.h>

typedef int ElementType;

typedef struct LinkedNode *LinkedList;

struct LinkedNode {

    ElementType Data;

    LinkedList link;

    int Address,Next;

};

LinkedList Delete(LinkedList Head, LinkedList

*DeleteRear);

void PrintLinkedList(LinkedList Head);

int main()

{

    int N,Head,Address,Key,Next;

    scanf("%d %d",&Head, &N);

    LinkedList Array[100000];

    int *AddressArray = malloc(sizeof(int)*N);

    int i = 0;

   

while (N--) {

        scanf("%d %d %d",&Address,&Key,&Next);

        Array[Address] = malloc(sizeof(struct LinkedNode));

        Array[Address]->Data = Key;

        AddressArray[i++] = Address;

        Array[Address]->Address = Address;

        Array[Address]->Next = Next;

    }

    for (i = i-1; i>=0; i--) {

        if (Array[AddressArray[i]]->Next == -1) {

            Array[AddressArray[i]]->link = NULL;

        }else

        {

            Array[AddressArray[i]]->link = Array[Array[AddressArray[i]]->Next];

        }

    }

    LinkedList head = Array[Head];

    LinkedList DeleteHead = malloc(sizeof(struct LinkedNode));

    DeleteHead->link = NULL;

    LinkedList Rear = DeleteHead;

    head = Delete(head, &Rear);

    PrintLinkedList(head);

    PrintLinkedList(DeleteHead->link);

    return 0;

}

LinkedList Delete(LinkedList Head, LinkedList *DeleteRear)

{

    LinkedList Result = Head;

    while (Head) {

        LinkedList Temp = Head->link;

        LinkedList Last = Head;

        while (Temp) {

            if (Temp->Data == Head->Data || -(Temp->Data) == Head->Data) {

                (*DeleteRear)->link = Temp;

                *DeleteRear = Temp;

                Last->link = Temp->link;

            }

            Last = Temp;

            Temp = Temp->link;

        }

        Head = Head->link;

    }

    (*DeleteRear)->link = NULL;

    return Result;

}

void PrintLinkedList(LinkedList Head)

{

    while (Head) {

        printf("%05d %d ",Head->Address,Head->Data);

        if (Head->link == NULL) {

            printf("-1\n");

        }else

        {

            printf("%05d\n",Head->link->Address);

        }

        Head = Head->link;

    }

}