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

原题

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*/
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值