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 class Solution {
public ListNode swapPairs(ListNode head) {
List<Integer> list = new ArrayList<Integer>();
ListNode node = new ListNode(0);
ListNode h = node;
while(head != null){
list.add(head.val);
head = head.next;
}
int[] nums = new int[list.size()];
for(int i = 0; i<list.size();i = i+2){
if(i + 1 > list.size() -1) {
nums[i] = list.get(i);
}else {
nums[i] = list.get(i+1);
nums[i+1] = list.get(i);
}
}
for(int i = 0;i < nums.length;i++){
ListNode n = new ListNode(nums[i]);
h.next = n;
h = h.next;
}
return node.next;
}
}
7.26更新
这道题目涉及到链表,肯定是希望用指针的思想来做,下面这种方法就是用到了指针,通过指针指向不同的位置来更换节点的顺序。
<span style="font-size:18px;">public ListNode swapPairs(ListNode head) {
if(head == null) return null;
if(head.next == null) return head;
ListNode first = new ListNode(-1);
first.next = head;
ListNode ptr1 = first;
ListNode ptr2 = first.next;
while(ptr1 != null && ptr2 != null && ptr2.next != null) {
ListNode nextNode = ptr2.next.next;
ptr1.next = ptr2.next;
ptr1.next.next = ptr2;
ptr2.next = nextNode;
ptr1 = ptr2;
ptr2 = nextNode;
}
return first.next;
}</span>