当前位置: 首页 > news >正文

【算法】判断一个链表是否为回文结构

问:

给定一个单链表的头节点head,请判断该链表是否为回文结构

例:

1 -> 2 -> 1返回true;1 -> 2 -> 2 -> 1返回true;15 -> 6 -> 15返回true

答:

笔试:初始化一个栈用来存放链表中右半部分的元素(快慢指针),弹栈的顺序是链表的逆序

public static class Node {public int value;public Node next;public Node(int data) {this.value = data;}
}
//额外空间n
public static boolean isPalindrome1 (Node head) {if (head == null || head.next == null) {return true;}Stack<Node> satck = new Stack<Node>();//为栈赋值做准备Node cur = head;//将链表的数据赋到栈中while (cur != null) {stack.push(cur);cur = cur.next;}//比较栈中的数据与链表中的数据while (head != null) {if (head.value != stack.pop().value) {return false;}head = head.next;}return true;
}
//额外空间n/2,快慢指针
public static boolean isPalindrome2 (Node head) {if (head == null || head.next == null) {return true;}Node slow = head.next;Node fast = head;while (fast.next != null && fast.next.next != null) {slow = slow.next;fast = fast.next.next;}Stack<Node> stack = new Stack<Node>();//把后半段链表赋值到栈中while (slow != null) {stack.push(slow);slow = slow.next;}//将弹栈元素与前半段链表中元素对比while (!stack.isEmpty()) {if (head.value != stack.pop().value) {return false;}head = head.next;}return true;
}

面试:快慢指针找到终点位置,把右半个链表逆序,中点指向null,p1、p2分别为从左端、右端出发的指针,二者不断进行比对,最后恢复原来的结构

//额外空间1
public static boolean isPalindrome3 (Node head) {if (head == null || head.next == null) {return true;}//找到链表中点Node slow = head;Node fast = head;while (fast.next != null && fast.next.next != null) {slow = slow.next;fast = fast.next.next;}//反转链表的后半段fast = slow.next;slow.next = null;Node n = null;while (fast != null) {n = fast.next;fast.next = slow;slow = fast;fast = n;}//将前半段与后半段比较n = slow;fast = head;boolean res = true;while (slow != null && fast != null) {if (slow.value != fast.value) {res = false;break;}slow = slow.next;fast = fast.next;}//把链表恢复原样slow = n.next;n.next = null;while (slow != null) {fast = slow.next;slow.next = n;n = slow;slow = fast;}return res;
}
http://www.lryc.cn/news/520128.html

相关文章:

  • 计算机网络之---ICMP协议与Ping命令
  • 【硬件介绍】Type-C接口详解
  • 【Pandas】pandas Series rtruediv
  • 项目开发版本控制Git流程规范
  • STM32 : 波特率发生器
  • STM32 USB组合设备 MSC CDC
  • 继续以“实用”指导Pythonic编码(re通配表达式)(2024年终总结2)
  • Flutter使用BorderRadiusTween实现由矩形变成圆形的动画
  • VSCode 中的 launch.json 配置使用
  • 深度学习张量的秩、轴和形状
  • Redis有哪些常用应用场景?
  • vue3+ts+element-plus 输入框el-input设置背景颜色
  • Ubuntu 磁盘修复
  • 使用RSyslog将Nginx Access Log写入Kafka
  • 通过Apache、Nginx限制直接访问public下的静态文件
  • uniapp小程序中隐藏顶部导航栏和指定某页面去掉顶部导航栏小程序
  • Agile Scrum 敏捷开发方法
  • 【算法与数据结构】—— 回文问题
  • 用vscode写latex-1
  • 爬虫基础之爬取歌曲宝歌曲批量下载
  • GitLab CI/CD使用runner实现自动化部署前端Vue2 后端.Net 7 Zr.Admin项目
  • web前端第五次作业---制作菜单
  • 软件系统安全逆向分析-混淆对抗
  • HAMi + prometheus-k8s + grafana实现vgpu虚拟化监控
  • Java基于SSM框架的在线视频教育系统小程序【附源码、文档】
  • mysql本地安装和pycharm链接数据库操作
  • Unity编程与游戏开发-编程与游戏开发的关系
  • 2025年第三届“华数杯”国际赛A题解题思路与代码(Python版)
  • 针对服务器磁盘爆满,MySql数据库始终无法启动,怎么解决
  • [Android]service命令的使用