Leetcode || Swap Nodes in Pairs
2015-11-04 11:02
639 查看
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.
遍历索引,0,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.
遍历索引,0,1,2,3…索引为偶数就和后面一个把值换了
package pack; class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class Solution { public ListNode swapPairs(ListNode head) { if(head==null) { return head; } ListNode p = head; int i = 0; while(p.next!=null) { if(i%2==0) { p.val = p.val ^ p.next.val; p.next.val = p.val ^ p.next.val; p.val = p.val ^ p.next.val; } i++; p = p.next; } return head; } } public class Main { static public void main(String[] args) { ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(3); n1.next = n2; n2.next = n3; n3.next = null; System.out.println(n1.val); System.out.println(n1.next.val); System.out.println(n1.next.next.val); new Solution().swapPairs(null); System.out.println("--------------------"); System.out.println(n1.val); System.out.println(n1.next.val); System.out.println(n1.next.next.val); } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解