2020年1月14日 星期二

Linked List--Delete

刪除第N個node
#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node *next;
};
struct Node *head;
void Print()
{
    struct Node *temp=head;
    while(temp!=NULL)
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
    printf("\n");
}
void Delete(int n)
{
    struct Node *temp1=head;
    if(n==1)
    {
        head=temp1->next;
        free(temp1);
        return;
    }
    for(int i=0;i<n-2;i++)
        temp1=temp1->next; //temp1 points to (n-1)th Node
    struct Node *temp2=temp1->next; //nth node
    temp1->next=temp2->next; //(n+1)th Node
    free(temp2); //Delete temp2
}
void Insert(int n)
{
    struct Node *temp1=(struct Node*)malloc(sizeof(struct Node));
    temp1->data=n;
    temp1->next=NULL;
    struct Node *temp2=head;
    if(temp2==NULL)
    {
        head=temp1;
        return;
    }
    while(temp2->next!=NULL) // not while(temp2!=NULL)
    {
        temp2=temp2->next;
    }
    temp2->next=temp1;
}
int main()
{
    head=NULL; //empty list
    int n;
    char c,ch;
    Insert(1);
    Insert(2);
    Insert(3);
    Insert(4); // 1 2 3 4
    Print();
    Delete(2); // 1 3 4
    Print();
    return 0;
}

以值刪除node
#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};
struct node *head;
void print()
{
    struct node *temp=head;
    while(temp!=NULL)
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
    printf("\n");
}
void insert(int data,int n)
{
    struct node *temp1=(struct node*)malloc(sizeof(struct node));
    temp1->data=data;
    temp1->next=NULL;
    if(n==1)
    {
        temp1->next=head;
        head=temp1;
        return ;
    }
    struct node *temp2=head;
    if(temp2==NULL&&n>1)
    {
        printf("error!\n");
        return ;
    }
    for(int i=0;i<n-2;i++)
    {
        temp2=temp2->next;
        if(temp2==NULL)
        {
            printf("error!\n");
            return ;
        }
    }
        
    temp1->next=temp2->next;
    temp2->next=temp1;
}
void delete(int n)
{
    int i=0;
    struct node *temp1=head;
    struct node *temp2=head;
    while(temp1!=NULL)
    {
        if(temp1->data==n) //points to n
        {
            if(i==0)
            {
                head=temp1->next;
                free(temp1);
                return ;
            }
            temp2->next=temp1->next;
            free(temp1);
            return ;
        }
        temp2=temp1;//temp2 is temp1-1
        temp1=temp1->next;
        i++;
    }
    printf("no this number!\n");
}
int main()
{
    head=NULL;
    int n,p;
    while(1)
    {
        printf("enter number to insert in list: ");
        scanf("%d",&n);
        if(n<0)
            break;
        printf("enter insert position: ");
        scanf("%d",&p);
        insert(n,p);
        print();
    }
    printf("delete one number: ");
    scanf("%d",&p);
    delete(p);
    print();
    return 0;
}

沒有留言:

張貼留言