码迷,mamicode.com
首页 > 其他好文 > 详细

1.3.20

时间:2018-05-01 20:51:58      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:turn   import   static   origin   rgs   before   length   first   1.3   

question:

Write a method delete() that takes an int argument k and deletes the kth element in a linked list, if it exists.

answer:

import edu.princeton.cs.algs4.*;

public class Linklist<Item>
{
    private static class Node<Item>
    {
        Item item;
        Node<Item> next;
    }
    
    public Node<Item> delete(int k, Node<Item> first)//删除第k节点
    {
        Node<Item> curr = first;
        int length = 0;
        while(curr.next != null)
        {
            length++;
            curr = curr.next;
        }
        if(k < 0 || k > length || first == null)
            return null;
        if(k == 0)
        {
            first = first.next;
            return first;
        }
        Node<Item> delete = first.next;
        Node<Item> before_delete = first;//删除节点delete就要知道它前一个节点
        int count = 1;
        while(count <= length)
        {
            if(count == k)
            {
                before_delete.next = delete.next;//删除节点delete
            }
            count++;
            delete = delete.next;
            before_delete = before_delete.next;
        }
        
        return first;
    }
    
    public static void main(String[] args)
    {
        Node<String> f = new Node<String>();
        Node<String> s = new Node<String>();
        Node<String> t = new Node<String>();
        Node<String> fo = new Node<String>();
        f.item = "a";
        f.next = s;
        s.item = "b";
        s.next= t;
        t.item = "c";
        t.next = fo;
        fo.item = "d";
        fo.next = null;
        StdOut.println("original link list:");
        Node head = f;
        while(head.next != null)
        {
            StdOut.print(head.item + " ");
            head = head.next;
        }
        StdOut.println(head.item);
        
        StdOut.println("input num n to delete the n node:(0-3)");//0-3
        int n = StdIn.readInt();
        
        StdOut.println("after delete the n node:");
        Linklist<String> linklist = new Linklist<String>();
        Node head2 = linklist.delete(n,f);//删除第n个节点
        if(head2 != null)
        {
            while(head2.next != null)
            {
                StdOut.print(head2.item + " ");
                head2 = head2.next;
            }
            StdOut.println(head2.item);
        }
    }
}

 

1.3.20

标签:turn   import   static   origin   rgs   before   length   first   1.3   

原文地址:https://www.cnblogs.com/w-j-c/p/8976803.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!