leetcode-24. Swap Nodes in Pairs
题目:
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.
感觉没什么要说的,,都是常规思路,链表加哑节点,然后循环条件判断是否为空,剩下的就是指针互相指了。细心一点就好
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dump = new ListNode(0);
ListNode ret = dump;
dump.next = head;
while(dump.next != null && dump.next.next != null){
ListNode tmp = dump.next;
dump.next = tmp.next;
tmp.next = dump.next.next;
dump.next.next = tmp;
dump = dump.next.next;
}
return ret.next;
}
}