LeetCode-Easy部分标签为LinkedList 206. Reverse Linked List

本文详细介绍了单链表反转的算法实现过程,包括使用Java和C语言版本的代码示例。通过逐步分析,读者可以了解如何有效地进行链表反转,并提供了一个容易出错的代码版本供对比学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

Reverse a singly linked list.

题目分析


这里写图片描述

  1. 保存节点b后的所有节点顺序
  2. 上步保存后,可以放心的将b的next域指向a,实现反转
  3. 上步实现反转后,再赋值给a,这样a始终为反转链表的头节点
  4. 上步后实现了反转,这步实现迭代,即让b再在原来的链表中保持前行。

实现代码


        public ListNode ReverseList(ListNode head)
        {
            if (head == null || head.next == null)
                return head;
            ListNode a = head;        
            ListNode b = head.next;
            a.next = null;
            while (b != null)
            {
                ListNode tmp = b.next; //保存节点b后的所有节点顺序
                b.next = a; //上步保存后,可以放心的将b的next域指向a,实现反转
                a = b; //上步实现反转后,再赋值给a,这样a始终为反转链表的头节点
                b = tmp;//上步后实现了反转,这步实现迭代,即让b再在原来的链表中保持前行。
            }
            return a;
        }

LinkedList的更多题目

http://blog.csdn.net/daigualu/article/details/69077428

随着学习的深入,对反转链表有了更深层次的认识,现记录到这里:
C语言版本:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
#include <stdlib.h>
#include <stdio.h>

struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL) return NULL;
    struct ListNode *rev_head = head; /*reversed-listnode head*/    
    struct ListNode *cur_head = head->next; /*original listnode head*/
    rev_head->next = NULL;
    while(cur_head!=NULL) {
        struct ListNode *next = cur_head->next; /*save next for original listnode head*/
        cur_head->next = rev_head; /*current head points to reversed-list head*/
        rev_head = cur_head; /*reversed-list head points to current head*/
        cur_head = next; /*current head points to saved next node*/
    }
    return rev_head; /*return rev_head that consistently points to reversed-list head*/
}

以下是一个错误版本:仅有两行代码的顺序反了,

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
#include <stdlib.h>
#include <stdio.h>

struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL) return NULL;
    struct ListNode *rev_head = head; /*reversed-listnode head*/
     rev_head->next = NULL;    
    struct ListNode *cur_head = head->next; /*original listnode head*/   
    while(cur_head!=NULL) {
        struct ListNode *next = cur_head->next; /*save next for original listnode head*/
        cur_head->next = rev_head; /*current head points to reversed-list head*/
        rev_head = cur_head; /*reversed-list head points to current head*/
        cur_head = next; /*current head points to saved next node*/
    }
    return rev_head; /*return rev_head that consistently points to reversed-list head*/
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值