1.3.26

question;

write a method remove() that takes a linked list and a string key as arguments and removes all of the nodes in the list that have key as its item field.

answer:

import edu.princeton.cs.algs4.*;

public class Linklist
{
    private static class Node//节点
    {
        String item;
        Node next = null;
    }
    
     public Node create(int n)//创建链表
    {
        Node head = null;
        Node p1 = head;
        Node p2;
        for(int i = 0; i < n; i++)
        {
            p2 = new Node();
            StdOut.println("input the string of node " + i + ":");
            p2.item = StdIn.readString();
            if(head == null)
            {
               head = p1 = p2;
            }
            else
            {
               p1.next = p2;
               p1 = p2;
            }
        }
        p1.next = null;
        return head;
    }
   
    public void show(Node head)//遍历链表
    {
        Node current = head;
        while(current != null)
        {
            StdOut.print(current.item + "\t");
            current= current.next;
        }
        StdOut.print("\n");
    }
    
    public Node remove(Node head, String key)
    {
        while(head.item.equals(key))//排除head的item为key的情况
        {
            head = head.next;
        }
        Node current = head.next;//已排除head的item是key的情况了
        Node before_current = head;
        while(current != null)
        {
            if(current.item.equals(key))//删除后,current和before_current不是指向next就行了的
            {
                Node temp = current;
                before_current.next = current.next;
                before_current = temp;
                current = current.next;
                continue;
            }
            current = current.next;
            before_current = before_current.next;
        }
        return head;
    }
    
    public static void main(String[] args)
    {
        Node head;
        int n;
        Linklist linklist = new Linklist();
        StdOut.println("input the length of linklist:(>0)");
        n = StdIn.readInt();
        head = linklist.create(n);
        linklist.show(head);
        StdOut.println("input the string key to detele nodes that has it:");
        String key;
        key = StdIn.readString();
        head = linklist.remove(head,key);
        linklist.show(head);
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9060134.html