首页 > 代码库 > 链表的基本操作(元素删除,插入,链表生成,链表倒置)

链表的基本操作(元素删除,插入,链表生成,链表倒置)

 

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct stu{
    int d;
    struct stu *l;
}st;
void xj(st *h)//生成单链表
{
    st *l;
    l=h;
    int m;
    scanf("%d",&m);
    h=(st *)malloc(sizeof(st));
    while(m--)
    {
        st *s;
        s=new st;
        scanf("%d",&s->d);
        l->l=s;
        l=s;
    }
    l->l=NULL;
}
void shc(st *h)//输出链表
{
    h=h->l;
    while(h->l!=NULL)
    {
        printf("%d ",h->d);
        h=h->l;
    }
    printf("%d\n",h->d);
}
void chr(st *h)//按大小插入元素
{
    int n;
    scanf("%d",&n);
    h=h->l;
    while(h!=NULL)
    {
      if(n<=h->l->d)
      {
           st *s;
           s=new st;
           s->d=n;
         s->l=h->l;
           h->l=s;
           break;
      }
      else
       h=h->l;
    }
}
void shac(st *h)//删除链表第n个元素
{
    int n;
    scanf("%d",&n);
     int k=0;
    while(h!=NULL)
    {
        if(k==n-1)
        {
          st *s;
          s=new st;
          s=h->l;
          h->l=h->l->l;
          free(s);break;
          }    
        h=h->l;
        k++;
    }
}
void dz(st *h)//倒置链表
{
    st *l;
    l=new st;
    l=h->l->l;
    h->l->l=NULL;
    while(l!=NULL)
    {
      st *s;
      s=new st;
      s->d=l->d;
      s->l=h->l;
      h->l=s;
      l=l->l;
    }
}
int main()
{ 
    st *h,*h1; 
    h=new st;
    h1=new st;
    h=h1;
    xj(h);
    h=h1;
    shc(h);
    h=h1;
    chr(h);
    h=h1;
    shc(h);
    h=h1;
    shac(h);
    h=h1;
    shc(h);
    h=h1;
    dz(h);
    shc(h);
    return 0;
}

 

链表的基本操作(元素删除,插入,链表生成,链表倒置)