当前位置:网站首页>奇偶链表[链表操作的两种大方向]
奇偶链表[链表操作的两种大方向]
2022-07-01 00:39:00 【REN_林森】
链表操作的两种大方向
前言
链表操作有两种方式,一种是简便操作,就在链表上操作;一种是非常nice的全能型操作,设置dummy节点,可以统一空链表/第一节点操作,把满足条件的节点以头插/尾插放到dummy之后。
一、链表操作的两种大方向

二、dummy
package everyday.listNode;
// 奇偶链表
public class OddEvenList {
/* target:先奇后偶,把偶数放前面,奇数放后面。 链表操作有两种方式,一种是简便操作,就在链表上操作; 一种是非常nice的全能型操作,设置dummy节点,可以统一空链表/第一节点操作,把满足条件的节点以头插/尾插放到dummy之后。 */
public ListNode oddEvenList(ListNode head) {
int cnt = 1;// 先奇后偶/先偶后奇,把同类的按顺序尾插法放在一起。
ListNode dummy1 = new ListNode();
ListNode p1 = dummy1;
ListNode dummy2 = new ListNode();
ListNode p2 = dummy2;
// 获取奇偶链表。
while (head != null) {
// 拿到处理好的节点。
ListNode node = head;
head = head.next;// 先走到下一个节点,好把上一个节点处理干净。
node.next = null;
if ((cnt & 1) == 1) {
p1.next = node;
p1 = p1.next;
}
if ((cnt & 1) == 0) {
p2.next = node;
p2 = p2.next;
}
// 标识下一个奇偶。
cnt = ++cnt & 1;
}
// 将两条链表相连。
p1.next = dummy2.next;
return dummy1.next;
}
// 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;
}
}
}
总结
1)操作链表的两种方式,一般推荐dummy法。如果是很简单的链表操作,也可以直接原地链表操作。
参考文献
边栏推荐
- 解析融合学科本质的创客教育路径
- Koa koa-combine-routers 分路由管理
- Unit test concept and purpose
- HDU 2488 A Knight's Journey(DFS)
- Practical shell knowledge
- Shift operators
- Detailed analysis of operators i++ and ++i in JS, i++ and ++i
- NE555 waveform generator handle tutorial NE555 internal structure (I)
- Left join displays the specified value when the left join matching data is null
- Get to know the drawing component of flutter - custompaint
猜你喜欢

What if the disk of datanode is full?

The longest selling mobile phone in China has been selling well since its launch, crushing iphone12

NE555波形发生器手把手教程之NE555内部结构(一)

Set different background colors for the border and text of the button

Sword finger offer 18 Delete the node of the linked list

From January 11, 2007 to January 11, 2022, I have been in SAP Chengdu Research Institute for 15 years

Unit test concept and purpose

酒旅板块复苏,亚朵继续上市梦,距离“新住宿经济第一股“还有多远?

SAP ui5 beginner tutorial 19 - SAP ui5 data types and complex data binding

Multi graph explanation of resource preemption in yarn capacity scheduling
随机推荐
优质的水泵 SolidWorks模型素材推荐,不容错过
Pytorch auto derivation
软硬件基础知识学习--小日记(1)
2022 is half way through. It's hard to make money
初识 Flutter 的绘图组件 — CustomPaint
集群与LVS介绍及原理解析
Vnctf 2022 cm CM1 re reproduction
ArrayList分析1-循环、扩容、版本
C # Generate PPK files in Putty format (passthrough support)
Mindjet mindmanager2022 mind map decompression installer tutorial
Set different background colors for the border and text of the button
TCP三次握手为什么不是两次或四次
Unit test concept and purpose
Oracle-数据完整性
对libco的一点看法
The communication mechanism and extension of Supervisor
Listview in flutter application development
Chapter 53 overall understanding of procedures from the perspective of business logic implementation
Length of the longest integrable subarray
K210门禁毕设