题目链接:. - 力扣(LeetCode)
思路一:数学逻辑,由于链表结构比较难操作,将其先放入集合或者数组中,方便处理,随后两两交换,如果后面元素不够交换了,则最后一个元素不用交换。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null){
return head;
}else{
List<Integer> list =new ArrayList();
while(head!=null){
list.add(head.val);
head=head.next;
}
int[] arr=new int[list.size()];
for(int i=0;i<list.size();i=i+2){
int j=i+1;
if(j==list.size()){
arr[i]=list.get(i);
break;
}
arr[i]=list.get(j);
arr[j]=list.get(i);
}
ListNode res=new ListNode(0);
ListNode cur=res;
for(int item:arr){
ListNode node=new ListNode(item);
cur.next=node;
cur=cur.next;
}
return res.next;
}
}
}
思路二:利用指针操作原链表,需要注意的是原链表元素个数是奇数还是偶数,这将影响到循环终止条件,并且一定是双与而不是双或。其中双或主要是为了锁住原链表元素个数为奇数个的情况。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null){
return head;
}else{
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode cur=dummy;
while(cur.next!=null&&cur.next.next!=null){
ListNode tmp=cur.next;
ListNode tmp1=cur.next.next.next;
cur.next=cur.next.next;
cur.next.next=tmp;
tmp.next=tmp1;
cur=cur.next.next;
}
return dummy.next;
}
}
}