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

/**
*
*问题:删除链表的中间节点
* 给定链表的头节点head, 实现删除链表的中间节点的函数。
*
*分析:
* 不删除任何节点;
* 1->2, 删除节点1;
* 1->2->3, 删除节点2;
* 1->2->3->4, 删除节点2:
* 1->2->3->4->5, 删除节点3;
*
* 如果链表为空或者长度为1, 不需要调整, 则直接返回;
* 如果链表的长度为2, 将头节点删除即可;
* 当链表长度到达3, 应该删除第2个节点; 当链表长度为4, 应该删除第2个节点;
* 当链表长度为5, 应该删除第3个节点……
*
*结论:
* 也就是链表长度每增加2(3,5,7 ...), 要删除的节点就后移一个节点, 如果要删除一个节点, 则需要找到待删除节点的前一个节点。
* @author 雪瞳
*
*/

public class Node<T> {
    public T value;
    public Node<T> next;
    public Node(T data){
        this.value = data;
    }
}
public class DeleteCenterNode {
	
		private Node pre;
		private Node cur;
	public Node deleteCenterNode(Node head) {
		//链表为空或长度为 1 直接返回
		if(head==null && head.next==null) {
			return head;
		}
		//链表长度为2 删除头结点
		if(head.next.next == null) {
			head  = head.next;
			return head;
		}
		//链表长度大于3
		pre = head;
		cur = head.next.next;
		//从头结点开始遍历 就由于每长度每增加 2就会导致删除结点后移一个结点,所以只要遍历的尾部结点无法达到增加2的情况
		//当前pre结点的下一结点就是需要删除的结点
		while(cur.next !=null && cur.next.next !=null) {
			pre = pre.next;
			cur = cur.next.next;
		}
		//移除pre的下一个结点
		pre.next = pre.next.next;
		return head;
		
	}
}

  

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

public class testDeleteCenterNode {
    public static void main(String[] args) {
        DeleteCenterNode delete = new DeleteCenterNode();
        testDeleteCenterNode test = new testDeleteCenterNode();
        Random rand = new Random();    
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入链表长度");
        int K = 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.deleteCenterNode(head);
        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/12503179.html