2022/12/09拓展班上机课题解

题目: 链表逆置

在这里插入图片描述
在这里插入图片描述

解析

链表:
在这里插入图片描述

初始

front = head;
front_next = front->next;

在这里插入图片描述

循环

第一轮循环

front->next = new_head;

在这里插入图片描述

new_head = front;

在这里插入图片描述

front = front_next;

在这里插入图片描述

front_next = front->next;

在这里插入图片描述

第二轮循环

front->next = new_head;

在这里插入图片描述

new_head = front;

在这里插入图片描述

front = front_next;

在这里插入图片描述

front_next = front->next;

在这里插入图片描述

第三次循环

第四次循环

第五次循环

第六次循环

第六次循环的初始状态
在这里插入图片描述

front->next = new_head;

在这里插入图片描述

new_head = front;

在这里插入图片描述

front = front_next;

在这里插入图片描述

if(front==NULL) break;

判断条件满足,退出循环。

在这里插入图片描述
返回new_head

代码

#include <stdio.h>
#include <stdlib.h>

struct ListNode {
    int data;
    struct ListNode *next;
};
struct ListNode *reverse( struct ListNode *head ){
    if(!head) return NULL;
    
    struct ListNode *new_head = NULL;
    struct ListNode *front,*front_next;
    
    front = head;
    front_next = front->next;
    
    while(1){
        front->next = new_head;
        new_head = front;
        
        front = front_next;
        if(front==NULL) break;
        front_next = front->next;
    }
    
    return new_head;
    
}
//创建链表
struct ListNode *createlist(){
    struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
    head->data = 1;

    struct ListNode *point1 = (struct ListNode *)malloc(sizeof(struct ListNode));
    point1->data = 2;
    head->next = point1;

    struct ListNode *point2 = (struct ListNode *)malloc(sizeof(struct ListNode));
    point2->data = 3;
    point1->next = point2;

    struct ListNode *point3 = (struct ListNode *)malloc(sizeof(struct ListNode));
    point3->data = 4;
    point2->next = point3;

    struct ListNode *point4 = (struct ListNode *)malloc(sizeof(struct ListNode));
    point4->data = 5;
    point3->next = point4;

    struct ListNode *point5 = (struct ListNode *)malloc(sizeof(struct ListNode));
    point5->data = 6;
    point4->next = point5;

    struct ListNode *point6 = (struct ListNode *)malloc(sizeof(struct ListNode));
    point6->data = -1;
    point5->next = point6;

    point6->next = NULL;

    return head;

}
//打印
void printlist( struct ListNode *head )
{
     struct ListNode *p = head;
     while (p) {
           printf("%d ", p->data);
           p = p->next;
     }
     printf("\n");
}
int main()
{
    struct ListNode  *head;

    head = createlist();
    head = reverse(head);
    printlist(head);
    
    return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值