先看一眼题:
草稿纸上画个图,就知道指针该怎么连了,草稿纸太乱了,就不贴了,直接上代码吧:
public static ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
if(head.next.next==null){
head.next.next=head;
ListNode p = head.next;
head.next=null;
return p;
}
ListNode p=null,q=null,r=null,pre=null,res=null;
boolean first = true;
p=head;
q=p.next;
r=q.next;
while (q!=null){
q.next=p;
p.next=r;
if(pre!=null)
pre.next=q;
try {
r = r.next;
}catch (NullPointerException e){
r=null;
}
pre=q;
if(first){
res =pre;
first=false;
}
q=p.next;
try {
r = r.next;
}catch (NullPointerException e){
r=null;
}
try {
q = q.next;
}catch (NullPointerException e){
q=null;
}
p=p.next;
pre=pre.next;
}
return res;
}
最后
以上就是霸气音响最近收集整理的关于力扣第24题 中等难度 两两交换链表中的节点的全部内容,更多相关力扣第24题内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复