题意:
给定一个链表,交换每两个相邻节点并返回其头部。
例如,
在1->2->3->4中,您应该返回列表as2->1->4->3。
您的算法应该只使用常量空间。不能修改列表中的值,只能更改节点本身。
如果是基数,最后一个节点不需要交换
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null) return head;
//表示节点2个以上
ListNode pre = head;
ListNode cur = head.next;
ListNode tmp = cur.next;
cur.next = pre;//2-1
pre.next = tmp;//1-3
head = cur;
if(tmp==null||tmp.next==null) return head;//只有2或3个节点
cur = tmp;
tmp = tmp.next;//往后移了一位
while(cur!=null&&tmp!=null){
pre.next = tmp;
cur.next = tmp.next;
tmp.next = cur;
//交换完毕
//后退两步
pre = cur;
if(cur.next==null) break;
cur = cur.next;
tmp = cur.next;
}
return head;
}
}