[算法]删除链表的中间节点

题目一:

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

思路:

基本解法:

先遍历一遍链表,计算出链表节点的个数。然后计算出中间节点的位置,再次遍历链表,找到中间节点的前一个位置,进行删除操作。

但是也可以只遍历一次就完成上述操作:

链表的长度 中间节点 的位置
1 1
2 1
3 2
4 2
5 3
6 3
7 4
8 4

可以看出,链表的长度每增加两个节点,中间节点的位置就向右移动一位。所以我们可以设置两个变量pre和cur,cur表示当前遍历的位置,pre表示从头结点到cur这段的中间节点的前一个节点的位置。在遍历链表的过程中,cur一次向右移动两个节点,那么pre就一次向右移动一个节点。当然,上述过程要注意判断cur.next及cur.next.next是否为空。当一次遍历完成后,cur指向最后一个节点或者倒数第二个节点,而pre指向整个链表中间节点的前一个节点的位置。

  public static class Node {
    public int value;
    public Node next;
    public Node(int data) {
      this.value = data;
    }
  }
  public static 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 = pre.next;
      cur = cur.next.next;
    }
    pre.next = pre.next.next;
    return head;
  

找到链表的中间节点是链表算法中十分常用。注意灵活应用。

posted @ 2016-03-07 12:56  小魔仙  阅读(376)  评论(0编辑  收藏  举报