目录
一、题目
二、思路
既然是要均分为三等份,则需要计算下结点的数量是否为3的倍数
是:l1、l2、l3三个指针同时走、直至l3.next==head;
否:需要将l1、l2先向前走K步,随后l3再走、直至l3.next==head;
int K=(int)Math.round(count * 1.0 / 3)-1;
三、代码
@Test public void GetThreeListNode(){ ListNode l0 = new ListNode(0); ListNode l1 = new ListNode(0); ListNode l2 = new ListNode(1); ListNode l3 = new ListNode(2); ListNode l4 = new ListNode(3); ListNode l5 = new ListNode(4); ListNode l6 = new ListNode(5); ListNode l7 = new ListNode(6); ListNode l8 = new ListNode(7); ListNode l9 = new ListNode(8); l0.next=l0; l1.next = l2; l2.next = l3; l3.next = l4; l4.next = l5; l5.next = l6; l6.next = l7; l7.next = l8; l8.next = l1; l9.next = l1; List<ListNode> listNodeList = getThreeListNode(l1); // 打印结果 for (int i = 1; i <= listNodeList.size(); i++) { System.out.println("第"+i+"个ListNode"); ListNode listNode = listNodeList.get(i-1); while (listNode!=null){ System.out.println(listNode.val+"、"); listNode=listNode.next; } } } private List<ListNode> getThreeListNode(ListNode head) { // 初始化三个需要返回的链表 ListNode l1 = null; ListNode l2 = null; ListNode l3 = null; List<ListNode> list = new ArrayList<>(); // 特殊情况 head 为空 if(head==null){ return list; } // 只有一个结点不成环 if(head.next==null){ list.add(head); return list; } // 结点大于1,统计结点个数 int count =1; ListNode temp = head; while (temp.next!=head){ ++count; temp=temp.next; } // 自身成环 if(count==1){ ListNode a1 =temp.next; l1=a1; a1.next=null; list.add(l1); return list; } // 有两个结点且成环 if(count==2){ ListNode a1 =temp.next; l1=a1; a1.next=null; l2=temp; temp.next=null; list.add(l1); list.add(l2); return list; } // 结点大于3时,先判断结点数是不是3的倍数 if (count % 3 == 0) { l1 = head; l2 = head.next; l3 = head.next.next; ListNode a1 ; ListNode a2 ; ListNode a3 ; while (l3.next != head) { l1 = l1.next; l2 = l2.next.next; l3 = l3.next.next.next; } a1 = l1.next; a2 = l2.next; a3 = l3.next; l1.next = null; l2.next = null; l3.next = null; l1 = a1; l2 = a2; l3 = a3; } else { l1 = head; l2 = head.next; l3 = head.next.next; ListNode a1 ; ListNode a2 ; ListNode a3 ; int k = (int) Math.round(count * 1.0 / 3) - 1; while (k != 0) { l1 = l1.next; l2 = l2.next.next; k--; } while (l3.next != head) { l3 = l3.next; } a1 = l1.next; a2 = l2.next; a3 = l3.next; l1.next = null; l2.next = null; l3.next = null; l1 = a1; l2 = a2; l3 = a3; } System.err.println("count:"+count); list.add(l1); list.add(l2); list.add(l3); return list; }