• [LeetCode]Reverse Linked List


    题目描述:(链接)

    Given a singly linked list, determine if it is a palindrome.

    解题思路:

    使用快慢指针,找到链表的中心点,然后逆序后一半链表,最后再一一比较!

     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     bool isPalindrome(ListNode* head) {
    12         if (head == nullptr) return true;
    13         
    14         ListNode *slow = head;
    15         ListNode *fast = head;
    16         while (fast != nullptr && fast->next != nullptr) {
    17             slow = slow->next;
    18             fast = fast->next->next;
    19         }
    20         
    21         // 逆序后一半链表
    22         if (fast != nullptr) {
    23             fast = reversedListedArray(slow->next);
    24         } else {
    25             fast = reversedListedArray(slow);
    26         }
    27         
    28         slow = head;
    29         while (slow != nullptr && fast != nullptr) {
    30             if (slow->val != fast->val) {
    31                 return false;
    32             }
    33             slow = slow->next;
    34             fast = fast->next;
    35         }
    36         
    37         return true;
    38     }
    39 private:
    40     ListNode *reversedListedArray(ListNode *head) {
    41         if (head == nullptr) return head;
    42         
    43         ListNode dummy(-1);
    44         dummy.next = head;
    45         ListNode *prev = dummy.next;
    46         ListNode *cur = prev->next;
    47         while (cur != nullptr) {
    48             prev->next = cur->next;
    49             cur->next = dummy.next;
    50             dummy.next = cur;
    51             cur = prev->next;
    52         }
    53         return dummy.next;
    54     }
    55 };
  • 相关阅读:
    c#基础 里氏转换
    c#基础 base和this的区别,在继承上面
    c#基础值类和引用类型_字符串
    c# 基础字符串
    c#基础-构造函数 this new
    c#基础3-方法的重载静态和非静态,字段属性,方法
    c#基础2-out-ref
    .net的基础知识点
    Xamarin.Form的坑
    weboack 4 tutorial
  • 原文地址:https://www.cnblogs.com/skycore/p/4946412.html
Copyright © 2020-2023  润新知