首页 > 其他分享 >LeetCode: 234. Palindrome Linked List

LeetCode: 234. Palindrome Linked List

时间:2022-12-05 18:04:02浏览次数:46  
标签:Palindrome return val List back next front 234 ListNode


LeetCode: 234. Palindrome Linked List

题目描述

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

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:
Could you do it in ​​​O(n)​​​ time and ​​O(1)​​ space?

解题思路 —— 递归求解

递归地求得当前节点对应的对称节点,比较它们的值是否一致。

AC 代码

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
private:
// time: O(n), space: O(1)
bool cmpList(ListNode* front, ListNode*& back)
{
if(front == nullptr) return true;

if(front->next == nullptr && back->val == front->val)
{
back = back->next;
return true;
}
else if(front->next == nullptr && back->val != front->val)
{
return false;
}
else if(cmpList(front->next, back) == false)
{
return false;
}
else if(back->val == front->val)
{
back = back->next;
return true;
}
else
{
return false;
}
}

public:
bool isPalindrome(ListNode* head)
{
return cmpList(head, head);
}
};


标签:Palindrome,return,val,List,back,next,front,234,ListNode
From: https://blog.51cto.com/u_15903085/5913207

相关文章

  • java并发数据结构之CopyOnWriteArrayList
    CopyOnWriteArrayList是一个线程安全的List实现,其在对对象进行读操作时,由于对象没有发生改变,因此不需要加锁,反之在对象进行增删等修改操作时,它会先复制一个对象副本,然后对......
  • DevExpress TreeList使用心得
    最近做项目新增光纤线路清查功能模块,思路和算法已经想好了,些代码时候居然在一个控件上纠结了好长的时间,虽然后来搞定了,但是好记性不然烂笔头,还是写下来,以后要用到的时候直接......
  • DevExpress TreeList 调优_绑定数据源方式, 放弃原来的AppendNode加载数据的方式
    注意事项1:由于一旦绑定了数据源dataTable的些许变化便在TreeList中有所体现,所以等dataTable完全填充好了之后再绑定数据源.注意事项2:dataTable每行的父节点ID当加载到......
  • virsh list报错: error: failed to connect to the hypervisor
    查看本地kvm虚机时,发现无法查看,出现报错#virshlisterror:failedtoconnecttothehypervisorerror:Failedtoconnectsocketto'/var/run/libvirt/libvirt-soc......
  • vba-传递listbox作为参数
    '反选PrivateSubCommandButton1_Click()CallTestss(Me!TIListBox)EndSubPrivateFunctionTestss(ByReflbAsObject)Iflb.ListCount<1ThenMsgBox......
  • 使用list和数组保存数据的差别
    在上位机开发曲线供能时遇到一个疑惑的问题,但又感觉这个问题太基础,想求证一下。需求:一共有1000个模拟量数据,每个数据记录600个点作为一组数据曲线,那么这1000个模拟量需要......
  • HACKTHEBOX VM LIST
    LinuxBoxes:WindowsBoxes:MorechallengingthanOSCP,butgoodpractice:LamelegacyJeeves[Windows]brainfuckBlueBart[Windows]shockerDevel......
  • vba-ArrayList
    TIListBox.MultiSelect=1TIListBox.ListStyle=1TIListBox.ColumnWidths=62TIListBox.ColumnCount=1Dimarr,brrC_Controlarr,b......
  • DevExpress 给TreeList添加右键菜单
    只有在右击节点时才会触发privatevoidtreeList1_MouseDown(objectsender,MouseEventArgse){if(e.Button==MouseButtons.Right)......
  • 操作Devexpress treelist中的项
    如果需要在单元格添加时则用TreeList如果只是单纯读取数据或检索数据时则用GridControl​​​​1.如果点击添加时则添加TreeList的节点:protectedinternalvoidbtnAdd_Cli......