(节点交换,不能使用值交换,特别注意这个要求)
划分成子问题,设要交换的节点为X1和X2节点,用tail来接收后续尾部。那么X2——>X1——>tail。然后让已经排好的——>Xi2.
/**
* 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)return null;
if(head.next==null)return head;
ListNode res=head.next;
ListNode pre=null;
while(head!=null&&head.next!=null){
if(pre!=null)pre.next=head.next;
ListNode tail=head.next.next;
head.next.next=head;
head.next=tail;
pre=head;
head=head.next;
}
return res;
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- ovod.cn 版权所有 湘ICP备2023023988号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务