单链表基本操作:创建、插入、删除、获取

来源:互联网 发布:java main函数 多线程 编辑:程序博客网 时间:2024/06/03 10:39
#include <stdio.h>#include <stdlib.h>typedef struct LNode{    int data;    struct LNode *next;}LNode,*LinkList;//创建一个含有n个元素的单链表LNode *createList(int n){    LNode *head = NULL,*p1,*p2;    for(int i=1;i<=n;i++)    {        p1 = (LinkList)malloc(sizeof(LNode));        if(p1==NULL)            return NULL;        printf("输入链表中第%d个数",i);        scanf("%d",&p1->data);        if(head==NULL)        {            head = p1;            p2 = p1;        }else        {            p2->next = p1;            p2 = p1;        }    }    p2->next = NULL;    return head;}//初始化一个空链表LNode *initLink(){    LNode *head = (LNode *)malloc(sizeof(LNode));    if(head==NULL)        return NULL;    head->next = NULL;    return head;}//打印链表void printList(LNode *head){    LNode *p = head;    while(p!=NULL){        printf("%d  ",p->data);        p = p->next;    }}//在链表第i位插入一个值LNode  *insertList(LNode *head,int m,int k){    LNode *p = head;    if(m==1)    {        LNode *q = (LNode *)malloc(sizeof(LNode));        q->data = k;        q->next = head;        head = q;    }    else    {        for(int i=1;i<m-1 && p!=NULL;i++)        {            p = p->next;        }        if(p==NULL)        {            printf("error");            exit(1);        }        LNode *q = (LNode *)malloc(sizeof(LNode));        q->data = k;        q->next = p->next;        p->next = q;    }    return head;}//删除链表第i个元素LNode *deleteList(LNode *head,int k){    LNode *p = head,*q;    if(k==1)    {        q = head;        head = head->next;        free(q);    }    else    {        for(int i=1;i<k-1 && p!=NULL;i++){            p = p->next;    }        q = p->next;        p->next = p->next->next;        free(q);    }    return head;}//获得链表第i个元素值int getEleList(LNode *head, int k){    LNode *p = head;    for(int i=1;i<k && p!=NULL;i++)    {        p = p->next;    }    return p->data;}int main(int argc, char *argv[]) {    //创建顺序链表    LNode *head1 = createList(5);    printList(head1);    printf("\n")    //插入元素测试    head1 = insertList(head1,3,0);    printList(head1);    printf("\n");    head1 = deleteList(head1,3);    printList(head1);    printf("\n");    head1 = deleteList(head1,1);    printList(head1);    printf("\n");    printf("%d",getEleList(head1,3));    printf("\n");    return 0;}
0 0
原创粉丝点击