Middle-题目25:24. Swap Nodes in Pairs
来源:互联网 发布:四九算法是虚岁 编辑:程序博客网 时间:2024/05/16 01:19
题目原文:
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.
题目大意:
给一个单链表,两两交换相邻节点。
题目分析:
用Two Pointers,分别指向头结点和第二个节点,每次移动两步,注意处理结点个数为奇数(最后一次的时候p2->next为空,再取next会报错)的特殊情况。
源码:(language:java)
public class Solution { public ListNode swapPairs(ListNode head) { if(head == null || head.next == null) // This list has only 0 or 1 node. return head; ListNode l1=head,l2=head.next; while(l1!=null && l2!=null) { int temp=l1.val; l1.val=l2.val; l2.val=temp; l1=l1.next.next; l2=l2.next; if(l2==null) break; else l2=l2.next; } return head; }}
成绩:
0ms,beats 13.35%,众数0ms,86.65%
Cmershen的碎碎念:
这题很水,不知道为什么出现在Middle里面。
0 0
- Middle-题目25:24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- Middle-题目24:46. Permutations
- python学习网站
- 九度OJ 1052
- Android:TextView的垂直滚动效果,和上下滚动效果
- UE4 蓝图里添加Cpp文件,不在VS解决方案里显示的问题
- Middle-题目25:24. Swap Nodes in Pairs
- 使用自定义View绘制右侧导航栏
- 第十四周项目三 数组类模板
- 做题笔记
- C++常用排序算法总结
- Middle-题目26:216. Combination Sum III
- IAR中volatile使用
- s:iterator 的用法
- java面向对象(面试题)