每日一题 为了工作 2020 0405 第三十四题

/**
* 问题: 向有序的环形单链表中插入新节点
* 一个环形单链表从头节点 head开始不降序, 同时由最后的节点指回头节点。给定这样
* 一个环形单链表的头节点 head和一个整数 num, 请生成节点值为 num的新节点,并插入到
* 这个环形链表中, 保证调整后的链表依然有序。
*
* 解题:
* 1. 生成节点值为 num的新节点, 记为 node。
* 2. 如果链表为空, 让 node自己组成环形链表, 然后直接返回node。
* 3. 如果链表不为空, 令变量 pre=head, cur=head.next, 然后令 pre和 cur同步
* 移动下去, 如果遇到 pre的节点值小于或等于 num,并且 cur的节点值大于或等于 num,说
* 明 node应该在 pre节点和 cur节点之间插入, 插入 node, 然后返回 head即可。
* 例如, 链表 1->3->4->1->… , num=2。应该把节点值为 2的节点插入到 1和 3之间 ,
* 然后返回头节点。
* 4. 如果 pre和 cur转了一圈, 这期间都没有发现步骤 3所说的情况,说明 node应该插入
* 到头节点的前面, 这种情况之所以会发生, 要么是因为 node节点的值比链表中每个节总的值
* 都大, 要么是因为 node的值比链表中每个节点的值都小。
* 分别举两个例子:
* 示例1, 链表 1->3->4->1->… , num=5, 应该把节点值为 5 的节点,插
* 入到节点1 的前面;
* 示例2, 链表 1->3->4->1->…, num=O, 也应该把节点值为 0 的节点,插
* 入到节点1 的前面。
* 5. 如果 node节点的值比链表中每个节点的值都大, 返回原来的头节点即可:如果 node节点
* 的值比链表中每个节点的值都小, 应该把 node作为链表新的头节点返回。
*
* @author 雪瞳
*
*/

*代码

public class Node {
	public int value;
	public Node next;
	public Node(int data){
		this.value=data;
	}
}

  

public class InsertCircleNodeList {
	
		public Node insertCircleNodeList(Node head,int num){
			
			Node newHead = null;
			Node insert = new Node(num);
			Node preCurrent = null;
			Node current = null;
			int flag = 0;
			if(head==null){
				insert.next=insert;
				return insert;
			}
			
			preCurrent = head;
			current = head.next;
			while(current != head){
				if(preCurrent.value <= num && num <=current.value){
					preCurrent.next=insert;
					insert.next=current;
					flag = 1;
				}
				preCurrent=current;
				current=current.next;
			}
			if(flag == 0){
				insert.next=head;
				preCurrent.next=insert;
				
				if(head.value>num){
					return insert;
				}else if(head.value<num){
					return head;
				}
			}
			return head;
		} 
}

  

public class TestInsertCircleNodeList {

	public static void main(String[] args) {
		TestInsertCircleNodeList test = new TestInsertCircleNodeList();
		InsertCircleNodeList insert = new InsertCircleNodeList();
		
		Node n1 = new Node(1);
		Node n2 = new Node(2);
		Node n3 = new Node(3);
		Node n4 = new Node(4);
		Node n5 = new Node(6);
		
		n1.next = n2;
		n2.next = n3;
		n3.next = n4;
		n4.next = n5;
		n5.next = n1;
		
		Node head = n1;
		test.showNodeList(head);
		Node result = insert.insertCircleNodeList(head, 5);
		test.showNodeList(result);
		
	}
	
	public void showNodeList(Node head){
		int flag = 0;
		Node current = head.next;
		System.out.println("链表内元素如下...");
		System.out.print(head.value+"\t");
		while(current!=head){
			flag ++;
			System.out.print(current.value+"\t");
			current = current.next;
			if(flag == 5){
				System.out.println();
			}
		}
		System.out.println();
	} 
}

  

*运行结果

 

猜你喜欢

转载自www.cnblogs.com/walxt/p/12636732.html
今日推荐