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

1.3.19

时间:2018-05-01 20:39:50      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:read   block   一个   string   oid   delete   private   import   linked   

question:

 Give a code fragment that removes the last node in a linked list whose first node is first.

answer:

import edu.princeton.cs.algs4.*;

public class Linklist<Item>
{
    private static class Node<Item>
    {
        Item item;
        Node<Item> next;
    }
    
    public Node<Item> deletelastnode(Node<Item> first)
    {
        if(first == null || first.next == null)
            return null;
        
        Node<Item> last = first;
        while(last.next != null)//找尾节点
        {
            last = last.next;
        }
        
        Node<Item> sec_last = first;
        while(sec_last.next != last)//找尾节点前一个节点
        {
            sec_last = sec_last.next;
        }
        sec_last.next = null;//删除尾节点
        
        return first;
    }
    
    public static void main(String[] args)
    {
        Node<String> first = new Node<String>();
        Node<String> head = first;
        StdOut.println("input the length of link list:(>0)");
        int c = StdIn.readInt();
        for(int i = 0; i < c - 1; i++)//创建链表
        {
            Node<String> temp = new Node<String>();
            first.item = "a";
            first.next = temp;
            first = temp;
        }
        first.item = "last";
        first.next = null;
        StdOut.println("original link list:");
        Node<String> h1 = head;
        while(h1.next != null)
        {
            StdOut.print(h1.item + " ");
            h1 = h1.next;
        }
        StdOut.println(h1.item);
        StdOut.println("after delete:");
        Linklist<String> linklist = new Linklist<String>();//不是很懂
        Node<String> h2 = linklist.deletelastnode(head);
        if(h2 != null)
        {
            while(h2.next != null)
            {
               StdOut.print(h2.item + " ");
               h2 = h2.next;
            }
               StdOut.println(h2.item);
        }
    }
}

 

1.3.19

标签:read   block   一个   string   oid   delete   private   import   linked   

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

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