链表问题3——删除链表的中间节点(初阶)

题目

给定链表的头节点head,实现删除链表的中间节点的函数。

不删除任何节点
1—>2, 删除节点1
1—>2—>3,删除节点2
1—>2—>3—>4,删除节点2
1—>2—>3—>4—>5,删除节点3

思路

找到要删除节点的前一个节点即可。


源码

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

public Node removeMidNode(Node head){
	if(head==null||head.next==null){
		return head;
	}
	if(head.next.next==null){
		return head.next;
	}
	Node pre=head;
	Node cur=head.next.next;
	while(cur.next!=null&&cur.next.next!=null){
		//pre 走一步,cur走两步,这样cur刚好走完,pre走到删除的中间节点
		//因为cur本身的起点就是head走了两步,所以cur刚好走完时,
		//pre走到删除节点的前一个节点
		pre=pre.next;
		cur=cur.next.next;
	}
	pre.next=pre.next.next;
	return head;
}
发布了43 篇原创文章 · 获赞 21 · 访问量 4921

猜你喜欢

转载自blog.csdn.net/flying_1314/article/details/103836823