原文:
Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
EXAMPLE
Input: the node ‘c’ from the linked list a->b->c->d->e Result: nothing is returned, but the new linked list looks like a->b->d->e
译文:
实现一个算法来删除单链表中间的一个结点,只给出指向那个结点的指针。
例子:
输入:指向链表a->b->c->d->e中结点c的指针
结果:不需要返回什么,得到一个新链表:a->b->d->e
package chapter_2_LinkedLists;
import java.util.Scanner;
class Node_3 {
public char data;
public Node_3 next;
}
/**
* 无头指针,链表
*/
class LinkList_3 {
public Node_3 head;
public LinkList_3() {
head = null;
}
}
/**
* 实现一个算法来删除单链表中间的一个结点,只给出指向那个结点的指针。
*/
public class Question_2_3 {
/**
*
* 删除链表中间结点,只有指向中间结点引用,如果提供链表头结点
* 从前往后遍历,遇到下一个为中间结点停止,删除中间结点
*
*/
public static void deleteMiddleNode(LinkList_3 linkList, Node_3 middle) {
Node_3 cur;
cur = linkList.head;
// 表头结点
if(cur == middle) {
linkList.head = cur.next;
}
while(cur.next != middle) {
cur = cur.next;
}
cur.next = cur.next.next;
}
/**
*
* 删除链表中间结点,只有指向中间结点引用,如果不提供链表头结点
* 则可以中间结点middle往后遍历,把结点元素信息往前拷贝,删除最后结点
*
*/
public static void deleteMiddleNode(Node_3 middle) {
Node_3 cur = middle;
if(cur.next == null) {
// 标志结尾,最后一个结点
cur.data = '0';
}
while(cur.next.next != null) {
cur.data = cur.next.data;
cur = cur.next;
}
cur.data = cur.next.data;
cur.next = null;
}
/**
* 输出链表数据
*/
public static void printLinkList(LinkList_3 linkList) {
Node_3 cur = linkList.head;
while(cur != null && cur.data != '0') {
System.out.format("%5c", cur.data);
cur = cur.next;
}
System.out.format("\n");
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.nextLine();
while(num -- > 0) {
int m = scanner.nextInt();
LinkList_3 linkList = new LinkList_3();
char charArray[] = new char[m];
scanner.nextLine();
// 输入链表数据
String str = scanner.nextLine();
Node_3 cur = null;
Node_3 middle = null;
for(int i=0; i< m; i++) {
Node_3 node = new Node_3();
node.data = str.charAt(i);
node.next = null;
if(i ==0) {
linkList.head = node;
cur = linkList.head;
} else {
cur.next = node;
cur = node;
}
if(i == str.length()/2) {
middle = node;
}
}
System.out.format("删除中间结点之前\n");
printLinkList(linkList);
// deleteMiddleNode(linkList, middle);
deleteMiddleNode(middle);
System.out.format("删除中间结点之后\n");
printLinkList(linkList);
}
}
}