当前位置:网站首页>链表、栈、队列
链表、栈、队列
2022-08-10 05:36:00 【吉良吉影__.】
链表 (2级标题)
1.反转链表( LeetCode 206 )(4级标题)
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null)return null;
ListNode pre = head;//前一个节点
ListNode cur = pre.next;//当前要插入的节点
ListNode next = null;//下一个待插入的节点
pre.next = null;
while (cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;//pre即为最终的头节点(最后一个插入链表中的节点)
}
}
2.相交链表( LeetCode 160 )
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode tempa = headA;
ListNode tempb = headB;
while (tempa != tempb){
tempa = tempa == null ? headB : tempa.next;
tempb = tempb == null ? headA : tempb.next;
}
return tempa;
}
}
3.合并两个有序链表 ( LeetCode 21 )
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode cura = list1,curb = list2;
ListNode res = new ListNode();
ListNode tmp = res;
while (cura != null && curb != null){
//遍历
if (cura.val < curb.val){
tmp.next = cura;
cura = cura.next;
}else {
tmp.next = curb;
curb = curb.next;
}
tmp = tmp.next;
}
tmp.next = cura == null ? curb : cura;//处理剩余元素
return res.next;
}
}
4.分隔链表 ( LeetCode 86 )
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode minNode = new ListNode();
ListNode maxNode = new ListNode();
ListNode mintmp = minNode;
ListNode maxtmp = maxNode;
while (head != null){
if (head.val < x){
mintmp.next = head;
mintmp = mintmp.next;
}else {
maxtmp.next = head;
maxtmp = maxtmp.next;
}
head = head.next;
}
maxtmp.next = null;//防止环路
mintmp.next = maxNode.next;
return minNode.next;
}
}
边栏推荐
猜你喜欢
Deep learning TensorFlow entry environment configuration
中间件-Rocktmq
AR Foundation Editor Remote插件使用方法
VTK 初步 (1) ----- 可视化管线
以STM32F103C6T6为例通过配置CubeMX实现EXIT外部中断
51单片机ST188手持人体温度脉搏心率测量仪锂电池充电
Explain the principle of MySql index in detail
每日刷题(day02)——leetcode 622. 设计循环队列
Flutter的生命周期
GC0053-STM32单片机NTC热敏电阻温度采集及控制LCD1602
随机推荐
51单片机教室人数进出统计检测数码管显示装置红外传感器
动态规划、背包问题 6/28 121-124
溶液中重金属去除
超纯水抛光树脂
Unity热更新哪些事
mkfs.minix.c之minix_super_block.s_nzones获取解析
内核性能分析总结
在Unity中利用代码动态更改场景中的天空盒
从零开始构建Google Protocol Buffer / protobuf 的helloworld工程(超级详细)
STM32单片机OLED俄罗斯方块单片机小游戏
动态规划、背包问题 6/22 96-100
C陷阱与缺陷 个人阅读笔记
优先级队列,大小顶堆PriorityQueue
pytorch-10. Convolutional Neural Networks
【简易笔记】PyTorch官方教程简易笔记 EP1
STM32单片机RGB红蓝调光植物补光系统红光蓝光PWM调色调节亮度
Deep learning TensorFlow entry environment configuration
STM32单片机手机APP蓝牙高亮RGB彩灯控制板任意颜色亮度调光
享元模式-缓存池
分享一个专业TA的《Shader参考大全》