数据结构之链表初始化,插入,逆置,输出

#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct Node{
    int data;
    struct Node *next;
}Node,*LinkList;
bool InitList(LinkList &L){
    L=(Node*)malloc(sizeof(Node));
    if(L==NULL) return false;
    L->next=NULL;
    printf("InitList Successful!\n");
    return true;
}
bool ListInsert(LinkList &L,int e){
    Node *s,*p=L;
    s=(Node*)malloc(sizeof(Node));
    if(s==NULL) return false;
    while(p->next!=NULL){
        p=p->next;
    }
    s->data=e;
    p->next=s;
    s->next=NULL;
    return true;   
}
bool PrintList(LinkList L)
{
    Node *p=L->next;
    if(p==NULL) return false;
 while(p!=NULL)
     {
     printf("%d ",p->data);
     p=p->next;
}return true;}
void ListReverse(LinkList &L){ //将链表元素进行逆置
    Node *r,*p=L->next;//r指针用来记录下一个需要逆置的节点元素 //p指向当前需要逆置的节点元素
    L->next=NULL;      //L的next指针指向空,可以保证链表尾部为空,后期插入是在L和L的next之间插入
    while(p!=NULL){
        r=p->next;//r指向下一个逆置的节点
        p->next=L->next;//p的next指向L的next,第一个元素是指向空,后面的元素依次指向上一个元素
        L->next=p;//L的next指向p,即当前逆置元素
        p=r;//p再指向下一个逆置节点
    }
}
    
int main() {
    LinkList L;
    InitList(L);
    int a[10]={1,2,3,4,5,6,7,8,9,10},i=0;

    while(i<(sizeof(a)/4))
        ListInsert(L,a[i++]);
    PrintList(L);
    ListReverse(L);
     printf("\n");
    PrintList(L);

    return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Keep Doing this

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值