【链表&交换邻节点】Swap Nodes in Pairs
2014-04-05 23:28
453 查看
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.
链表操作,注意头结点,交换的pre节点是否为null
public class Solution {
public ListNode swapPairs(ListNode head) {
int k = 0;
ListNode p = head, pre=null;
while(p != null){
ListNode r = null;
k++;
if(k%2 == 0){//r指向要交换的第一节点,p指向要交换的第二个节点,pre指向第一个节点的前一个节点
if(pre == null){
r = head;
r.next = p.next;
p.next = r;
head = p;
pre = r;
}
else{
r = pre.next;
r.next = p.next;
p.next = r;
pre.next = p;
pre = r;
}
p = r.next;
}
else p = p.next;
}
return 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.
链表操作,注意头结点,交换的pre节点是否为null
public class Solution {
public ListNode swapPairs(ListNode head) {
int k = 0;
ListNode p = head, pre=null;
while(p != null){
ListNode r = null;
k++;
if(k%2 == 0){//r指向要交换的第一节点,p指向要交换的第二个节点,pre指向第一个节点的前一个节点
if(pre == null){
r = head;
r.next = p.next;
p.next = r;
head = p;
pre = r;
}
else{
r = pre.next;
r.next = p.next;
p.next = r;
pre.next = p;
pre = r;
}
p = r.next;
}
else p = p.next;
}
return head;
}
}
相关文章推荐
- 451. 两两交换链表中的节点(swap-nodes-in-pairs)(c++)----lintcode面试题之链表
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- LeetCode Swap Nodes in Pairs交换链表中的两个节点
- Swap Nodes in Pairs --成对交换链表节点(重重重)
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- (Java) LeetCode 24. Swap Nodes in Pairs —— 两两交换链表中的节点
- Swap Nodes in Pairs 链表交换相邻的节点
- [C++]LeetCode: 109 Swap Nodes in Pairs (交换相邻节点位置)
- Leet Code 24 Swap Nodes in Pairs - 成对交换节点 - Java
- LeetCode OJ:Swap Nodes in Pairs(成对交换节点)
- LeetCode 24. Swap Nodes in Pairs(交换节点)
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- [LintCode] Swap Nodes in Pairs 成对交换节点
- [LeetCode] 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-----成对翻转链表中的节点
- swap-nodes-in-pairs(单链表交换点对)
- Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置