Swap Nodes in Pairs
2015-07-19 15:59
531 查看
Problem: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.
处理链表中的两个节点,同时需要记录这两个节点的前一个和下一个节点。
例如处理上面的1,2,需要使用两个变量记录1之前的节点,2之后的节点3。
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.
处理链表中的两个节点,同时需要记录这两个节点的前一个和下一个节点。
例如处理上面的1,2,需要使用两个变量记录1之前的节点,2之后的节点3。
public ListNode swapPairs(ListNode head) { ListNode p=new ListNode(0); p.next=head; ListNode pre=p; if(head==null||head.next==null) return head; while(pre.next!=null&&pre.next.next!=null){ ListNode t=pre; pre=pre.next; t.next=pre.next; ListNode t1=pre.next.next; pre.next.next=pre; pre.next=t1; } return p.next; }
相关文章推荐
- node模块的载入及机制
- node及npm安装过程中的win环境变量设置
- Node:KMP之next数组
- [CareerCup] 2.3 Delete Node in a Linked List 删除链表的节点
- node-inspector使用方法
- 开始刷leetcode day71:Delete Node in a Linked List
- leetcode_237题——Delete Node in a Linked List(链表)
- Node.js笔记
- Leetcode NO.237 Delete Node in a Linked List
- [Leetcode 237, Easy] Delete Node in a Linked List
- #24 Swap Nodes in Pairs
- 19 Remove Nth Node From End of List
- 关于nodejs面试
- LeetCode 237 Delete Node in a Linked List
- Remove Nth Node From End of List
- LeetCode: Reverse Nodes in k-Group
- Delete Node in a Linked List
- 237-e-Delete Node in a Linked List
- leetcode | Reverse Nodes in k-Group
- Node.js开发环境配置