LeetCode24 Swap Nodes in Pairs 成对交换链表节点
2015-05-06 13:55
639 查看
题目:
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.
翻译:
给你一个链表,交换每两个相连的节点。
思路:
就是节点交换问题。只要保存头结点,且要理清交换的节点的位置问题。
代码:
首先得保证该节点和下一个节点存在。
接着就是交换问题。 假设 现在的链表是1->2->3->4 。首先创建个root节点,他的next指向头部。
第一次循环:pre指向root,head指向1,要交换12,首先的保存2的下一个节点3,用t表示,接着使得pre的next为2 ,即head的next;接着2的下一个节点为1,于是乎pre.next.next
= head.最后head的下一个为3,即head.next = t。
此时链表为2-1-3-4.此时使得指针跳2个。即pre指向1,head指向3即可。然后继续循环实现交换。
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 root = new ListNode(0);//创建个首节点指向链表开始 root.next = head; ListNode pre = root;//前一个节点 while(head!=null && head.next!=null) { ListNode t = head.next.next; pre.next = head.next; pre.next.next = head; head.next = t; pre = head; head = t; } return root.next; }
首先得保证该节点和下一个节点存在。
接着就是交换问题。 假设 现在的链表是1->2->3->4 。首先创建个root节点,他的next指向头部。
第一次循环:pre指向root,head指向1,要交换12,首先的保存2的下一个节点3,用t表示,接着使得pre的next为2 ,即head的next;接着2的下一个节点为1,于是乎pre.next.next
= head.最后head的下一个为3,即head.next = t。
此时链表为2-1-3-4.此时使得指针跳2个。即pre指向1,head指向3即可。然后继续循环实现交换。
相关文章推荐
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- leetcode24,交换链表相邻的节点
- leetcode-24,交换链表相邻节点,递归实现
- (Java) LeetCode 24. Swap Nodes in Pairs —— 两两交换链表中的节点
- LeetCode Swap Nodes in Pairs交换链表中的两个节点
- leetCode 24. Swap Nodes in Pairs (双数交换节点) 解题思路和方法
- LeetCode 24 Swap Nodes in Pairs (交换相邻节点)
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- [leetcode 24]Swap Nodes in Pairs-----成对翻转链表中的节点
- LeetCode - 24 - Swap Nodes in Pairs(交换链表结点)
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- Leetcode 160 寻找两链表的交叉节点
- [LeetCode-237] Delete Node in a Linked List(删除链表中节点)
- [LeetCode] Linked List Random Node 链表随机节点
- 交换链表中的相邻节点
- leetcode 328 --Odd Even Linked List 链表 双指针 移动节点
- [LeetCode] 判断两个链表是否有公共节点并返回第一个公共节点
- 两两交换链表中的节点
- 两两交换链表中的节点
- LeetCode 24 Swap Nodes in Pairs (链表 递归&&非递归)