每日一题 为了工作 2020 0317 第十五题

/**
* 题目:删除链表的a/b处节点
* 给定链表的头节点 head、整数 a和 b, 实现删除位于 a/b处节点的函数。
*
* 例如:
* 链表: 1->2->3->4->5, 假设a/b的值为r。
* 如果r等于0, 不删除任何节点;
* 如果r在区间(0, 1/5]上, 删除节点1;
* 如果r在区间(1/5, 2/5]上, 删除节点2;
* 如果r在区间(2/5, 3/5]上, 删除节点3;
* 如果r在区间(3/5, 4/5]上, 删除节点4;
* 如果r在区间(4/5 , 1]上, 删除节点5;
* 如果r大于 1, 不删除任何节点。
*
* 分析:
* 如何根据链表的长度n, 以及a与b的值决定该删除的节点是哪一个节点呢?
*
* 方法:
* 先计算doubler = ((double) (a * n)) / ((double) b)的值, 然后r向上取整之后的整数值代
*表该删除的节点是第几个节点。
*
* 例子:
*1.如果链表长度为7, a=5, b=7。
* r = (7*5)/7 = 5.0, 向上取整后为5, 所以应该删除第5个节点
*
*2.如果链表长度为7, a=5, b=6。
* r = (7*5)/6 = 5.8333 … , 向上取整后为6, 所以应该删除第6个节点。
*
*3.如果链表长度为7, a= 1, b=6。
* r = (7*1)/6 = 1.1666 … , 向上取整后为2, 所以应该删除第2个节点。
*
* @author 雪瞳
*
*/

public class Node<T> {
	public T value;
	public Node<T> next;
	public Node(T data){
		this.value = data;
	}
}

 

public class DeleteaBybNode {
	private Node cur;
	public Node deleteNodeByab(Node head,int a,int b) {
		if(head == null  || b==0) {
			return null;
		}
		if(a<1 || a>b) {
			return head;
		}
		int nodeLength =0;
		int index = 0;
		cur = head;
		//计算链表长度
		 while(cur!=null) {
			 nodeLength++;
			 cur = cur.next;
		 }
		//获取删除结点位置
		index = (int) Math.ceil((double)(nodeLength*a)/(double)b);
		if(index == 1) {
			head = head.next;
		}
		if(index > 1) {
			cur = head;
			//单链表找到要删除的前一个节点
			//若index = 3
			// head ->head.next->head.next.next->head.next.next.next
			// while循环前index的值
			// 2		1		 0
			//			cur
			//					 要删除的节点
			while(cur != null) {
				index --;
				
				if(index == 1) {
					//当index为1时说明cur是需要删除节点的前一个节点 直接移除cur的next节点即可
					cur.next = cur.next.next;
				}
				cur = cur.next;		
			}			
		}
		return head;
	} 	
}

  

import java.util.Random;
import java.util.Scanner;

public class testDeleteNodeByab {
	public static void main(String[] args) {
		DeleteaBybNode delete = new DeleteaBybNode();
		testDeleteNodeByab test = new testDeleteNodeByab();
		Random rand = new Random();	
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入链表长度");
		int K = sc.nextInt();
		System.out.println("请输入a的值");
		int a =sc.nextInt();
		System.out.println("请输入b的值");
		int b =sc.nextInt();
		
		Node nodes[]=new Node[K];
		for(int i=0;i<nodes.length;i++) {
			nodes[i]=new Node(rand.nextInt(20)+1);
		}
		for(int i =0;i<nodes.length-1;i++) {
			nodes[i].next=nodes[i+1];
		}
		Node head = nodes[0];
		//test
		test.showNode(head);
		delete.deleteNodeByab(head, a, b);
		test.showNode(head);
		
	}
	public void showNode(Node head) {
		System.out.println("链表内的元素如下所示...");
		while(head != null) {
			System.out.print(head.value+"\t");
			head = head.next;
		}
		System.out.println();
	}
}

*运行结果

猜你喜欢

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