zoukankan      html  css  js  c++  java
  • LeetCode 206 Reverse Linked List

    Problem:

    Reverse a singly linked list.

    A linked list can be reversed either iteratively or recursively. Could you implement both?

    Summary:

    翻转链表。

    Analysis:

    1. Iterative solution

     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 *pre = NULL;
    13         
    14         while (head != NULL) {
    15             ListNode *tmp = head->next;
    16             head->next = pre;
    17             pre = head;
    18             head = tmp;
    19         }
    20         
    21         return pre;
    22     }
    23 };

     2. Recursive solution

    若链表为n1->n2->...->nk-1->nk->nk+1->...->nm->NULL

    假设nk+1到nm的部分已翻转:n1->n2->...->nk-1->nk->nk+1<-...<-nm

    我们若要使nk+1的next指针指向nk,则我们需要做的是:nk->next->next = nk

    需要注意的是需要将n1的next指针指向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         if (head == NULL || head->next == NULL) {
    13             return head;
    14         }
    15         
    16         ListNode *tmp = reverseList(head->next);
    17         head->next->next = head;
    18         head->next = NULL;
    19         
    20         return tmp;
    21     }
    22 };

    Reference: https://leetcode.com/articles/reverse-linked-list/#approach-1-iterative-accepted

  • 相关阅读:
    css属性操作2(外边距与内边距<盒子模型>)
    css的属性操作1
    css伪类
    属性选择器二
    属性选择器1
    03_MySQL重置root密码
    02_Mysql用户管理之Navicat下载及安装
    18.扩散模型
    17.广播模型
    16.友谊悖论
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6012874.html
Copyright © 2011-2022 走看看