Swap Nodes in Pairs(easy)
2016-06-01 17:37
323 查看
【题目】
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.
【题意】
将链表临接的元素交换
【分析】
每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...
就是每次跳两个节点,后一个接到前面,前一个接到后一个的后面,最后现在的后一个(也就是原来的前一个)接到下下个结点(如果没有则接到下一个)
这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧,大家以后会经常遇到。
因为这是一遍过的算法,时间复杂度明显是O(n),空间复杂度是O(1)。
【实现】
public ListNode swapPairs(ListNode head) {
if(head == null)
return null;
ListNode helper = new ListNode(0);
helper.next = head;
ListNode pre = helper;
ListNode cur = head;
while(cur!=null && cur.next!=null)
{
ListNode next = cur.next.next;
cur.next.next = cur;
pre.next = cur.next;
if(next!=null && next.next!=null)
cur.next = next.next;
else
cur.next = next;
pre = cur;
cur = next;
}
return helper.next;
}
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.
【题意】
将链表临接的元素交换
【分析】
每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...
就是每次跳两个节点,后一个接到前面,前一个接到后一个的后面,最后现在的后一个(也就是原来的前一个)接到下下个结点(如果没有则接到下一个)
这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧,大家以后会经常遇到。
因为这是一遍过的算法,时间复杂度明显是O(n),空间复杂度是O(1)。
【实现】
public ListNode swapPairs(ListNode head) {
if(head == null)
return null;
ListNode helper = new ListNode(0);
helper.next = head;
ListNode pre = helper;
ListNode cur = head;
while(cur!=null && cur.next!=null)
{
ListNode next = cur.next.next;
cur.next.next = cur;
pre.next = cur.next;
if(next!=null && next.next!=null)
cur.next = next.next;
else
cur.next = next;
pre = cur;
cur = next;
}
return helper.next;
}
相关文章推荐
- webStorm进行nodeJs开发
- [leetcode] 【链表】19. Remove Nth Node From End of List
- Leetcode 之Populating Next Right Pointers in Each Node II(51)
- Node.js学习
- Delete Node in a Linked List
- node.js调试
- Node.js Express目录结构
- Mac下安装Node.js服务器
- 嵌入式开发语言 -- nodejs
- HDFS 文件权限
- Eclipse下Nodejs项目配置步骤
- node.js npm mysql 相关
- 转“近期nodejs-web开发的一些总结”,大家都差不多
- nodejs的zookeeper模块及web管理工具node-zk-browser的安装
- nodejs中npm常用命令
- 读书笔记之《深入浅出Node.js》(4)
- 深入理解node exports和module.exports区别
- node to traverse cannot be null!
- Hard-题目14:25. Reverse Nodes in k-Group
- Hard-题目6:117. Populating Next Right Pointers in Each Node II