2020年1月13日 星期一

Linked List--Insert

我是看這個影片自學的,因為上課老師講的聽不懂。影片雖然是印度腔英文,但有字幕不難看懂,可以自己先畫圖理解過後在實作。

insert at beginning
//Linked List: Inserting a node at beginning
#include <stdio.h>
#include <stdlib.h>
struct Node
{
    int data;
    struct Node *next;
};
struct Node *head;
void Insert(int x)
{
    struct Node *temp=(struct Node *)malloc(sizeof(struct Node));
    temp->data=x;
    temp->next=head;
    head=temp;
}
void Print()
{
    struct Node *temp=head;
    printf("List is: ");
    while(temp!=NULL)
    {
        printf(" %d",temp->data);
        temp=temp->next;
    }
    printf("\n");
}
int main()
{
    
    head=NULL; //empty List
    printf("How many numbers?\n");
    int n,x;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        printf("Enter the number:\n");
        scanf("%d",&x);
        Insert(x);
        Print();
    }
    return 0;
}

insert at the end
//insert a node at the end
#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 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;
    while(1)
    {
        printf("enter the number:(0 to quit) ");
        scanf("%d",&n);
        if(n==0)
            break;
        Insert(n);
        Print();
    }
    return 0;
}

insert node at nth position
#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;
    for(int i=0;i<n-2;i++)
    {
        temp2=temp2->next;
    }
    temp1->next=temp2->next;
    temp2->next=temp1;
}
int main()
{
    head=NULL; //empty list
    Insert(2,1);//List: 2
    Insert(3,2);//List: 2,3
    Insert(4,1);//List:4,2,3
    Insert(5,2);//List:4,5,2,3
    Print();
    return 0;
}

沒有留言:

張貼留言