奇偶链表 --java 记录

在这里插入图片描述
第一种
创建两个链,将奇偶分开插入链中,最后奇偶链连接起来。

class Solution {
     public ListNode oddEvenList(ListNode head) {
	        if(head == null || head.next == null) return head;
	         //记录当前遍历节点位子
	      ListNode l1h = head;   //奇数链 头节点
	      ListNode l1 = l1h ;
	      ListNode l2h =head.next; //偶数链头节点
	      ListNode l2 = l2h;
          ListNode node = head.next.next; 

	        int n = 1;
	        while(node != null) {
	        	if(n % 2 != 0) {
	        		l1.next = node;
	        		 
	        		l1 = l1.next;
	        	}else {
	        		l2.next = node;
	        		 
	        		l2 = l2.next; 
	        	}
	        	node = node.next;
                n++;
	        }
	        l2.next = null;
         	l1.next = l2h;
	        return l1h ;
	        
	    }
}

第二种
直接在原链表的基础设置奇偶节点,分别为l1,l2然后上插入。
奇节点需要连接的节点为偶节点的下一个节点 表示为: l1. next = l2.next。
更新 奇节点位子 l1 = l1.next 。
偶节点需要连接的节点为奇节点的下一个节点 表示为: l2.next = l1.next。
循环后,将l1与 l2的头节点拼接

class Solution {
      public ListNode oddEvenList(ListNode head) {
	      if(head == null || head.next == null) return head;

	      ListNode l1 = head;   //奇数链 
	      ListNode l2 = head.next; //偶数链
	      ListNode l2h = l2; //偶数链头节点
	      while(l2 != null && l2.next != null) {
	        	l1.next = l2.next;
	        	l1 = l1.next;
	        	l2.next = l1.next;
	        	l2 = l2.next;
	        	 
	      }
	      l1.next = l2h;
	      return head ;
	        
	    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值