#include <stdio.h>
#include <conio.h>
typedef struct node
{
        int data;
        node *next;
};
void xem(node *first)
{
     node *p;
    p=first;
    while(p!=NULL)
    {
                  printf("%d",p->data);
                  p=p->next;
    }
}
node *nhap(node *first,node *last,int n)
{
     node *p;
     for(int i=0;i<n;i++)
     {
             p=new(node);
             scanf("%d",&p->data);
             p->next=NULL;
             if(first==NULL)
             {
                            first=p;
                            last=p;
             }
             else
             {
                 last->next=p;
                 last=p;
             }
     }
     return first;
}
node *xoadau(node *first)
{
     node *p;
     p=first;
     if(first==NULL)
     return first;
     first=p->next;
     delete(p);
     return first;
}
node *xoanodek(node *first)
{
     int k;
     printf("\nnhap vao so thu thu k muon xoa:  ");
     scanf("%d",&k);
     node *p,*q;
     int dem=1;
     p=first;
     if(k==1)
     return xoadau(first);
     while(dem<k)
     {
                   p=p->next;
                   dem++;
     }
     q=first;
     while(q!=NULL && q->next!=p)
     q=q->next;
     q->next=p->next;
     return first;
}
node *xoanodesauk(node *first)
{
     int k;
     printf("\nnhap vao so thu thu k muon xoa sau k la:  ");
     scanf("%d",&k);
     node *p,*q;
     int dem=1;
     p=first;
     while(dem<=k)
     {
                   p=p->next;
                   dem++;
     }
     q=first;
     while(q!=NULL && q->next!=p)
     q=q->next;
     q->next=p->next;
     return first;
}
node *xoanodetruock(node *first)
{
     int k;
     printf("\nnhap vao so thu thu k muon xoa truoc k la:  ");
     scanf("%d",&k);
     node *p,*q;
     int dem=1;
     p=first;
     if(k==2)
     return xoadau(first);
     while(dem<k-1)
     {
                   p=p->next;
                   dem++;
     }
     q=first;
     while(q!=NULL && q->next!=p)
     q=q->next;
     q->next=p->next;
     return first;
}

main()
{
      node *first=NULL,*last=NULL;
      int n;
      printf("nhap n: ");
      scanf("%d",&n);
      first=nhap(first,last,n);
      printf("\nxem: \n");
      xem(first);
      first=xoanodek(first);
      printf("\nxem: \n");
      xem(first);
      first=xoanodesauk(first);
      printf("\nxem sau khi xoa sau k la: \n");
      xem(first);
      first=xoanodetruock(first);
      printf("\nxem sau khi xoa truoc k la: \n");
      xem(first);
      getch();
}

Bài viết liên quan

Không có nhận xét nào:

Đăng nhận xét