• LC 206. Reverse Linked List


    题目描述

    Reverse a singly linked list.

    Example:

    Input: 1->2->3->4->5->NULL
    Output: 5->4->3->2->1->NULL

    参考答案

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* reverseList(ListNode* head) {
    12         ListNode* cur = NULL;
    13         while(head){
    14             ListNode * temp = head->next;
    15             head -> next = cur;
    16             cur = head;
    17             head = temp;
    18         }
    19         return cur;
    20     }
    21 };

    补充说明

    term 1:

    temp = 2 3 4 5 null

    head = 1 null = 1 2 3 4 5 null + null 

    cur = 1 null 

    head = 2 3 4 5 null 

    term 2:

    temp = 3 4 5 null

    head = 2 1 null ( 2 3 4 5 null + 1 null)

    cur = 2 1 null

    head = 3 4 5 null

    term 3:

    temp = 4 5 null

    head = 3 2 1 null = 3 4 5 null + 2 1 null

    cur = 3 2 1 null

    head = 4 5 null

    ......

  • 相关阅读:
    第07组 Alpha冲刺 (2/6)
    第07组Alpha冲刺(1/6)
    第四次作业
    面试题练习
    SpringMVC访问静态资源
    MyBatis基础
    Spring注解和jdk注解
    自动代理生成器
    aspect xml
    Spring-案例
  • 原文地址:https://www.cnblogs.com/kykai/p/11626906.html
Copyright © 2020-2023  润新知