这道题就是考验指针操作,难度不高,主要就是考验链表操作基本功
代码如下
public class swapPairs {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public static ListNode swapPairs(ListNode head) {
if(head==null || head.next==null)return head;
ListNode p1 = head;
ListNode p2 = head;
ListNode cur = head;
int count=1;
while(cur.next!=null){
//指针后移
p1=p2;
p2=cur;
cur=cur.next;
count++;
if(count%2==0){
//偶数的时候开始计算
if(count<=2){
//首位需要特殊处理
p2.next=cur.next;
cur.next=p2;
head = cur;
}else{
p2.next=cur.next;
p1.next=cur;
cur.next=p2;
}
//指针复位
ListNode temp = p2;
p2 = cur;
cur = temp;
}
}
return head;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(3);
ListNode l4 = new ListNode(4);
ListNode l5 = new ListNode(5);
ListNode l6 = new ListNode(6);
l1.next=l2;
l2.next=l3;
l3.next=l4;
l4.next=l5;
l5.next=l6;
ListNode r = swapPairs(l1);
while(r!=null){
System.out.print(r.val+"->");
r=r.next;
}
}
}
网友评论