单链表的输出、插入及删除

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//定义结构体
struct List
{
    int data;
    struct List* next;
};
//输入空表
void init(struct List** phead)
 {
     *phead=NULL;
 }
//求表长
 int getLength(struct List* head)
 {
     int len=0;
     while(head){
        len++;
        head=head->next;
     }
     return len;
 }
//输出链表
void printList(struct List* head)
{
    while(head){
        printf("%d ",head->data);
        head=head->next;
    }
    putchar('\n');
}
//创建节点
struct List* creatList(int x)
{
    struct List* t;
    t=(struct List*)malloc(sizeof(struct List));
    t->next=NULL;
    t->data=x;
    return t;
};
//查找第K项
struct List* findKth(struct List*head, int k)
{
    int count=1;
    struct List* p;
        p=head;
        while(p && count<k){
            p=p->next;
            count++;
        }
        return p;
};

//插入
int insert(struct List** phead, int k, int x)
{
    if(k<1)
        return 0;
    else if(k==1){
        struct List* t;
        t=creatList(x);
        t->next=*phead;
        *phead=t;
        return 1;
    }
    else{
        struct List* p;
        p=findKth(*phead, k-1);  //找到插入位置的前一项
        if(p){
            struct List* t;
            t=creatList(x);
            t->next=p->next;
            p->next=t;
            return 1;
        }
        else
            return 0;
    }
}
//删除
int removeList(struct List** phead, int k, int* px)
{
     if(k<1)
            return 0;
     else if(k==1){
        if(*phead){
            *px=(*phead)->data;
            *phead=(*phead)->next;
            return 1;
        }
        else
            return 0;
     }
     else{
          struct List* p;
          p=findKth(*phead, k-1);
          if(p==NULL || p->next==NULL)
            return 0;
          struct List* t;
          t=p->next;
          p->next=t->next;
          *px=t->data;
          free(t);
          return 1;
     }
}
int main()
{
    struct List* head;
    init(&head);
    int k = getLength(head);
    insert(&head,1,11);
    insert(&head,1,22);
    insert(&head,2,33);
    insert(&head,4,44);
    insert(&head,6,55);
    int x;
    removeList(&head,1,&x);
    printList(head);
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值