【华为机试048】从单向链表中删除指定值的结点

题目描述:

输入一个单向链表和一个节点的值,从单向链表中删除等于该值的节点,删除后如果链表中无节点则返回空指针。

链表结点定义如下:

struct ListNode

{

int       m_nKey;

ListNode* m_pNext;

};

详细描述:

本题为考察链表的插入和删除知识。

链表的值不能重复

构造过程,例如

1 <- 2

3 <- 2

5 <- 1

4 <- 5

7 <- 2

最后的链表的顺序为 2 7 3 1 5 4

删除 结点 2

则结果为 7 3 1 5 4

Java实现:

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int head = sc.nextInt();
            LinkedList<Integer> linkedList = new LinkedList<Integer>();
            linkedList.add(head);
            for (int i = 0; i < n-1; i++) {
                Integer next = sc.nextInt();
                Integer parent = sc.nextInt();
                int index = linkedList.indexOf(parent);
                linkedList.add(index+1, next);
            }
            Integer remove = sc.nextInt();
            linkedList.remove(remove);

            int i;
            for (i = 0; i < linkedList.size()-1; i++) {
                System.out.print(linkedList.get(i)+" ");
            }
            System.out.print(linkedList.get(i)+" ");
            System.out.println();
        }
    }


}


关键点:

  • 是linkedList.add(index+1, next)而不是linkedList.add(index+1, next),新插入值的索引是给出值的索引的下一个位置

猜你喜欢

转载自blog.csdn.net/heyiamcoming/article/details/81012452