当前位置:网站首页>24、两两交换链表中的节点(链表)
24、两两交换链表中的节点(链表)
2022-04-23 10:11:00 【Popuessing's Jersey】
题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
public class Liangliangjiaohuanlianbiaozhongdejiedian {
static class ListNode{
int val;//数据:节点的数据
ListNode next;//对象:节点的对象
ListNode(int val){
this.val = val;
}
}
public ListNode swapPairs(ListNode head){
//设置一个虚拟头节点
ListNode dummy = new ListNode(0);
dummy.next = head;
//定义当前节点
ListNode cur = dummy;
while (cur.next!=null && cur.next.next!=null){
//定义临时节点
ListNode temp = cur.next;
ListNode temp1= cur.next.next.next;
//步骤一
cur.next = cur.next.next;
//步骤二
cur.next.next = temp;
//步骤三
cur.next.next.next = temp1;
//cur移动两位进行下一轮交换
cur = cur.next.next;
}
return dummy.next;
}
//打印输出
static void print(ListNode listNode){
//创建链表节点
while (listNode!=null){
if(listNode.next==null){
System.out.print(listNode.val);
}else {
System.out.print(listNode.val + "->");
}
listNode = listNode.next;
}
}
public static void main(String[] args) {
//创建首节点
ListNode nodeSta = new ListNode(1);
//声明一个变量来表示移动过程中的当前节点
ListNode nextnode;
nextnode = nodeSta;
for (int i = 2; i <=6 ; i++) {
//生成新节点
ListNode node = new ListNode(i);
//移动节点指向新节点(连接新节点
nextnode.next = node;
//把当前节点往后移动
nextnode = nextnode.next;
}
//链表生成完毕
//直接从首节点打印
print(nodeSta);
System.out.println();
Liangliangjiaohuanlianbiaozhongdejiedian liangliangjiaohuanlianbiaozhongdejiedian = new Liangliangjiaohuanlianbiaozhongdejiedian();
ListNode res = liangliangjiaohuanlianbiaozhongdejiedian.swapPairs(nodeSta);
print(res);
}
}
时间复杂度:O(n)
空间复杂度:O(1)
版权声明
本文为[Popuessing's Jersey]所创,转载请带上原文链接,感谢
https://blog.csdn.net/CoCo629vanilla/article/details/121410596
边栏推荐
猜你喜欢
随机推荐
Redis design and Implementation
JVM——》常用命令
Rain produces hundreds of valleys, and all things grow
利用多线程按顺序连续输出abc10次
2022茶艺师(初级)考试试题模拟考试平台操作
Epidemic prevention registration applet
解决VMware卸载后再安装出现的问题
[codeforces - 208e] blood cousins
Using idea to develop Spark Program
2022 mobile crane driver test question bank simulation test platform operation
Career planning and implementation in the era of meta universe
Prefix sum of integral function -- Du Jiao sieve
Using multithreading to output abc10 times in sequence
Sim Api User Guide(7)
【无标题】
第二章 Oracle Database In-Memory 体系结构(上) (IM-2.1)
第三章 启用和调整IM列存储的大小(IM-3.1)
JUC concurrent programming 09 -- source code analysis of condition implementation
LeetCode-608. Tree node
杰理之有时候发现内存被篡改,但是没有造成异常,应该如何查找?【篇】