leetcode 24. Swap Nodes in Pairs
2016-06-28 13:00
1051 查看
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
这道题,考查数据结构。我选取三个指针。思路如下:
代码如下
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next==null){
return head;
}
ListNode a = head;
ListNode b = a.next;
ListNode c = null;
head = b;
while(a.next != null){
/*loop*/
a.next = a.next.next;
b.next = a;
c = a;
/*move*/
if(a.next == null){
break;
}
a = a.next;
if(a.next == null){
break;
}
b = a.next;
/*reassign c.next*/
c.next = b;
}
return head;
}
}
时间复杂度O(n), 空间复杂度O(1)。
在论坛上看到了用递归的,代码给简洁原地址。
public class Solution {
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}
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.
这道题,考查数据结构。我选取三个指针。思路如下:
代码如下
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next==null){
return head;
}
ListNode a = head;
ListNode b = a.next;
ListNode c = null;
head = b;
while(a.next != null){
/*loop*/
a.next = a.next.next;
b.next = a;
c = a;
/*move*/
if(a.next == null){
break;
}
a = a.next;
if(a.next == null){
break;
}
b = a.next;
/*reassign c.next*/
c.next = b;
}
return head;
}
}
时间复杂度O(n), 空间复杂度O(1)。
在论坛上看到了用递归的,代码给简洁原地址。
public class Solution {
public ListNode swapPairs(ListNode head) {
if ((head == null)||(head.next == null))
return head;
ListNode n = head.next;
head.next = swapPairs(head.next.next);
n.next = head;
return n;
}
}
相关文章推荐
- C#中list用法实例
- C#中Ilist与list的区别小结
- C#中IList<T>与List<T>的区别深入解析
- C#对list列表进行随机排序的方法
- Vc++ 控件List Control用法总结
- C++实现的泛型List类分享
- C#使用IComparer自定义List类实现排序的方法
- C# Datagridview绑定List方法代码
- javascript radio list的实现细节(多浏览器兼容)
- c++ STL容器总结之:vertor与list的应用
- java实现List中对象排序的方法
- 大家注意vector, list, set, map成员函数erase
- ASP.NET―001:GridView绑定List、页面返回值具体实现
- List all the Databases on a SQL Server
- js Map List 遍历使用示例
- Java比较两个List的值是否相等的方法
- Java List双击事件实现方法
- velocity显示List与Map的方法详细解析
- 关于STL中list容器的一些总结
- 关于C#泛型列表List<T>的基本用法总结