您的位置:首页 > 职场人生

删除链表中间节点

2016-12-15 00:26 204 查看

删除链表中间节点

[题目]

给定一个链表,然后实现删除链表中间节点的函数。

例如:

没有节点或者只有一个节点———不删除任何节点

1->2: 删除节点1

1->2->3: 删除节点2

1->2->3->4: 删除节点2

1->2->3->4->5: 删除节点3

[解答]

1.定义节点

package com.ahut;

public class Node {
public int data;
public Node next;

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


2.主要逻辑部分

package com.ahut;

public class Utils {

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;
if(cur.next != null && cur.next.next != null) {
//没增加两个节点,删除节点的序号就要加1
pre = pre.next;
cur = cur.next.next;
}
pre.next = pre.next.next;
return head;

}
}


3.测试部分

package com.ahut;

public class Test {

public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(6);

printLinkedList(head);
head = Utils.removeMidNode(head);
printLinkedList(head);
}

public static void printLinkedList(Node head) {
System.out.print("Linked List: ");
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}
}


4.测试结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息