关于链表的创建,删除,增添,遍历

                             **链表的操作**
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct link
{  int data;
   struct link *next;
};

struct link*creat(struct link*head)/*创建一个链表*/
{
    struct link *p=NULL,*pr=head;
    int data;
    p=(struct link*)malloc(sizeof(struct link));
    if(head==NULL)
    {
        head=p;
    }
    else
    {
        while(pr->next!=NULL)
        {
            pr=pr->next;
        }
        pr->next=p;
    }
    printf("Input node data");
    scanf("%d",&data);
    p->data=data;
    p->next=NULL;
    return head;

}

struct link*deletep(struct link*head,int a)/*删除一个链表*/
{
    struct link* pre;
    pre=head;
    int j=0;
    while(pre->next&&j<a-1)
    {
        pre=pre->next;
        j++;
    }
    pre->next=pre->next->next;
    return (head);
};

struct link*insertp(struct link*head,int pos,int a)/*插入链表*/
{
    struct link*pre,*p;
    p=(struct link*)malloc(sizeof(struct link));
    pre=head;
    int j=0;
    while(pre->next&&j<pos-1)
    {
        pre=pre->next;
        j++;
    }
    p->data=a;
    p->next=pre->next;
    pre->next=p;
    return(head);
};

void printlist(struct link *head)/*输出链表*/
{
    struct link *p;
   p=head;
    while (p!=NULL)
    {
        printf("%d",p->data);
        p=p->next;
    }
}
void main()/*主函数*/
{
    struct link *p,*head,*q;
    head=NULL;
    int i;
    for(i=0;i<8;i++)
    {
        head=creat(head);
    }
    p=insertp(head,1,0);
    printlist(p);
    printf("\n");
    q=deletep(head,3);
    printlist(q);
}

在这里插入图片描述

发布了9 篇原创文章 · 获赞 0 · 访问量 289

猜你喜欢

转载自blog.csdn.net/qq_45662882/article/details/101227282