删除链表的中间节点

来源:互联网 发布:php商城系统 开源 编辑:程序博客网 时间:2024/06/07 10:32

删除链表的中间节点:

参照博客:http://blog.csdn.net/StubbornAccepted/article/details/72356146

 public class Node<T>{
        T value;
        Node<T> next;


        public Node(T value) {
            this.value = value;
        }
        public String toString(){
            return value.toString();
        }
    }
    public Node<T> removeMid(Node head){//删除中间节点就是要找到中间结点的前一个节点
        if(head==null){
            return head;
        }
        if(head.next==null){
            return head;
        }
        Node<T> cur1=head;
        Node<T> cur2=cur1.next;
        while(cur2.next!=null&&cur2.next.next!=null){
            cur1=cur1.next;//cur1以一倍的速度向后移动。
            cur2=cur2.next.next;//cur2以二倍的速度向后移动。当cur2到达末尾时候,cur1也就达到了整个链表中间位置的前一个节点
        }
        cur1.next=cur1.next.next;
        return head;
    }