测试代码
package com.zhangyu;
public class LinkedListTest {
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
@Override
public String toString() {
if (this.next == null) {
return String.valueOf(this.data);
}
return this.data + "->" + this.next.toString();
}
}
public static Node removeNode(Node head, int position) {
if (head == null || position < 0) {
return head;
}
if (position == 0) {
head = head.next;
return head;
}
int curPosition = 1;
Node preNode = head;
Node curNode = head.next;
while (curNode != null) {
if (curPosition == position) {
preNode.next = curNode.next;
break;
}
curPosition++;
preNode = preNode.next;
curNode = curNode.next;
}
return head;
}
public static Node removeNode(Node head, Node removeNode) {
if (head == null || removeNode == null) {
return head;
}
if (removeNode == head) {
head = head.next;
return head;
}
if (removeNode.next == null) {
Node curNode = head;
while (curNode.next != removeNode) {
curNode = curNode.next;
}
curNode.next = null;
return head;
}
Node tmp = removeNode.next;
removeNode.data = tmp.data;
removeNode.next = tmp.next;
return head;
}
public static Node getTailNode(Node head) {
while (head.next != null) {
head = head.next;
}
return head;
}
public static void main(String[] args) {
Node head = createNewLinkedList();
System.out.println("新建一个链表:\n" + head);
System.out.println("删除尾节点:\n" + removeNode(head, 9));
System.out.println("删除中间节点:\n" + removeNode(head, 2));
System.out.println("删除头结点:\n" + removeNode(head, 0));
System.out.println("---------------------------");
head = createNewLinkedList();
System.out.println("新建一个链表:\n" + head);
System.out.println("删除尾节点:\n" + removeNode(head, getTailNode(head)));
System.out.println("删除中间节点:\n" + removeNode(head, head.next.next));
System.out.println("删除头结点:\n" + removeNode(head, head));
}
private static Node createNewLinkedList() {
Node head = new Node(0);
Node curNode = head;
for (int i = 1; i < 10; i++) {
curNode.next = new Node(i);
curNode = curNode.next;
}
curNode.next = null;
return head;
}
}
测试结果
新建一个链表:
0->1->2->3->4->5->6->7->8->9
删除尾节点:
0->1->2->3->4->5->6->7->8
删除中间节点:
0->1->3->4->5->6->7->8
删除头结点:
1->3->4->5->6->7->8
---------------------------
新建一个链表:
0->1->2->3->4->5->6->7->8->9
删除尾节点:
0->1->2->3->4->5->6->7->8
删除中间节点:
0->1->3->4->5->6->7->8
删除头结点:
1->3->4->5->6->7->8