Swap Nodes in Pairs:交换链表数组相邻元素的值
来源:互联网 发布:java企业级项目源代码 编辑:程序博客网 时间:2024/06/05 13:43
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路:从头遍历,每两个为一组,难点在于要注意null节点的判断,注意每组的第一个为空时就可以返回了。/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode swapPairs(ListNode head) { ListNode H = new ListNode(0); H.next = head; ListNode l , r; if(head==null){ return head; }else{ l = head; } if(head.next==null){ return head; }else{ r = head.next; } while(l!=null&&r!=null){ int temp = l.val; l.val = r.val; r.val = temp; System.out.println(l.val+" "+r.val); l = (r.next!=null)?r.next:null; if(l==null){ return H.next; } r = (l.next!=null)?l.next:null; } return H.next; }}
阅读全文
0 0
- Swap Nodes in Pairs:交换链表数组相邻元素的值
- Swap Nodes in Pairs 链表交换相邻的节点
- 交换单链表中相邻的两个元素 Swap Nodes in Pairs
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- Swap Nodes in Pairs 交换LinkList的相邻节点
- (LeetCode)Swap Nodes in Pairs --- 交换两个相邻的结点
- LeetCode OJ 之 Swap Nodes in Pairs (交换成对相邻结点的值)
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- 【leetcode】24. Swap Nodes in Pairs - 成对交换链表元素
- LeetCode24 Swap Nodes in Pairs 成对交换链表节点
- Leetcode Swap Nodes in Pairs 交换链表的节点对
- [C++]LeetCode: 109 Swap Nodes in Pairs (交换相邻节点位置)
- 24. Swap Nodes in Pairs(每两个相邻节点进行一次交换)
- Swap Nodes in Pairs 成对交换结点
- [LeetCode]Swap Nodes in Pairs 成对交换
- [LeetCode]Swap Nodes in Pairs 交换节点
- 【LeetCode】Swap Nodes in Pairs 链表指针的应用
- LeetCode Swap Nodes in Pairs交换链表中的两个节点
- sublime text安装ctags插件
- spring boot 入门
- 欢迎使用CSDN-markdown编辑器
- 【Vue】基于nodejs的vue项目打包编译部署
- AS中使用git
- Swap Nodes in Pairs:交换链表数组相邻元素的值
- mysql--16700练习
- NPM报错:node-pre-gyp install --fallback-to-build一直卡住不动了
- CentOS 7下更改yum源与更新系统
- ArcGIS:按照属性表字段分割矢量
- Java基础 3 运算
- git入门(msysgit安装)
- 【目标检测】Fast RCNN算法详解(转)
- Java 基础 4 流程控制语句