链表:调换相邻元素

    给定一个链表,把相邻的两个元素进行互换。

    如给定链表1->2->3->4->5->6,则互换后的结果为2->1->4->3->6->5。

    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)
        	return head;
        if(head.next.next == null){    //只有两个元素
        	head.next.next = head;
        	head = head.next;
        	head.next.next = null;
        	return head;
        }
        ListNode pre = head;
        ListNode curr = head.next;
        ListNode next = curr.next;
        head = head.next;
        while(true){
        	curr.next = pre;
        	if(next.next != null && next.next.next != null){    //正常往前循环
        	    pre.next = next.next;
        	 	pre = next;
    			curr = pre.next;
        	    next = next.next.next;
        	}
        	else if(next.next == null){    //到达尾部,且链表元素个数为奇数,直接把最后一个元素连接到末尾
        		pre.next = next;
        		break;
        	}
        	else if(next.next.next == null){    //到达尾部,且链表元素个数为偶数,进行最后一步互换,并设置结束符null
        		pre.next = next.next;
        		next.next.next = next;
        		next.next = null
        		break;
        	}
        }
        return head;
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值