【LeetCode】24. Swap Nodes in Pairs
来源:互联网 发布:网络女主播卸妆前后 编辑:程序博客网 时间:2024/05/19 23:16
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.
题目大意为给定一个链表,两两一组,交换链表中的节点。这道题比较好理解,也比较简单。要注意的就是交换链表中的节点和交换值不同,要注意指针指向 ,分别定义表示要交换两节点的前一个节点和下一个节点,避免节点丢失,并且增加头结点便于操作.
代码如下:
public ListNode swapPairs(ListNode head) { //定义一个头结点 ListNode head_prev=new ListNode(0); head_prev.next=head; //定义一个节点始终指向要交换节点的前一个节点 ListNode node_prev=head_prev; while(head!=null&&head.next!=null){ //定义一个节点用于保存要交换节点的下一个节点,避免丢失 ListNode node_next=head.next.next; //交换节点 node_prev.next=head.next; head.next.next=head; head.next=node_next; //交换完毕,向后移动两位 node_prev=node_prev.next.next; head=node_next; } return head_prev.next; }
0 0
- [LeetCode]24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs Leetcode Python
- LeetCode --- 24. Swap Nodes in Pairs
- LeetCode 24.Swap Nodes in Pairs
- [Leetcode] 24. Swap Nodes in Pairs
- 【LeetCode】24.Swap Nodes in Pairs
- [leetcode] 24.Swap Nodes in Pairs
- **LeetCode 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs LeetCode
- leetcode 24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- LeetCode--24. Swap Nodes in Pairs
- leetcode 24. Swap Nodes in Pairs
- 【LeetCode】24. Swap Nodes in Pairs
- [leetcode] 24. Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- LeetCode-24.Swap Nodes in Pairs
- LeetCode 24. Swap Nodes in Pairs
- iOS开发 通知传值
- VLAN
- 线程池,这一篇或许就够了
- 关于open()返回值及打印输出的问题
- linux gdb
- 【LeetCode】24. Swap Nodes in Pairs
- 动态规划―鸣人的影分身
- JStorm Storm 上手demo
- POJ2388简单排序
- 平面中能否写下不可数个8?——一个有趣的数学问题
- 设计模式学习笔记之单例模式
- 青春正当时
- 判断二叉树是否是平衡树
- Python中用format函数格式化字符串的用法