算法练习(38): 链表的增删查改4(1.3.28-1.3.31)

本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本人新建了一个微信群(算法交流),想要加入的,请添加我的微信号:zhujinhui207407 谢谢。另外,本人的个人博客 http://www.kyson.cn 也在不停的更新中,欢迎一起讨论

算法(第4版)

知识点

  • 链表节点增删查改
  • 环形链表

题目

1.3.28 用递归的方法解答上一道练习


1.3.28 Develop a recursive solution to the previous question.

题目

1.3.29 用环形链表实现Queue。环形链表也是一条链表,只是没有任何结点链接为空,且只要链表非空则last.next的值就为first。只能使用一个Node类型的实例变量(last)。


1.3.29 Write a Queue implementation that uses a circular linkedlist,which is the same as a linked list except that no links are null and the value of last.next is first when- ever the list is not empty. Keep only one Node instance variable (last).

答案

public class CircularLinkedListQueue<Item> implements Iterable<Item>{
    
    private class Node<Item> {
        Item item;
        Node<Item> next;
    }

    private Node<Item> last;
    private int N = 0;

    public void enqueue(Item item) {
        Node<Item> node = new Node<Item>();
        node.item = item;
        if (this.isEmpty()) {
            node.next = node;
            last = node;
            N++;
        }else {
            node.next = last.next;
            last.next = node;
            last = node;
            N++;
        }
    }

    public Item dequeue() {
        if (this.isEmpty()) {
            return null;
        }
        Node<Item> first = last.next;
        last.next = last.next.next;
        N--;
        return first.item;
    }

    public boolean isEmpty(){
        return last == null;
    }
    
    public Iterator<Item> iterator() {
        return new QueueIterator();
    }

    private class QueueIterator implements Iterator<Item>
    {
        Node<Item> current = last;
        int index = 0;
        
        public boolean hasNext() {
            if (last == null) {
                return false;
            }
            if (index < N) {
                return true;
            }
            return false;
        }

        public Item next() {
            current = current.next;
            index++;
            return current.item;
        }

        public void remove() {
            
        }
        
    }
    
    public static void main(String[] args) {
        CircularLinkedListQueue<String> queue = new CircularLinkedListQueue<String>();
        queue.enqueue("我的");
        queue.enqueue("名字");
        queue.enqueue("叫");
        queue.enqueue("顶级程序员不穿女装");
        queue.enqueue("微博:https://m.weibo.cn/p/1005056186766482");
        queue.dequeue();
        queue.dequeue();
        
        for (String string : queue) {
            System.out.println(string);
        }
        System.out.println(queue);      
    }   
}

代码索引

CircularLinkedListQueue.java

题目

1.3.30 编写一个函数,接受一条链表的首结点作为参数,(破坏性地)将链表反转并返回结果链表的首结点。

image.png

image.png


1.3.30 Write a function that takes the first Node in a linked list as argument and (de- structively) reverses the list, returning the first Node in the result.
Iterative solution : To accomplish this task, we maintain references to three consecutive nodes in the linked list, reverse, first, and second. At each iteration, we extract the node first from the original linked list and insert it at the beginning of the reversed list. We maintain the invariant that first is the first node of what’s left of the original list, second is the second node of what’s left of the original list, and reverse is the first node of the resulting reversed list.

public Node reverse(Node x)
{
   Node first   = x;
   Node reverse = null;
   while (first != null)
   {
      Node second = first.next;
      first.next  = reverse;
      reverse     = first;
      first       = second;
   }
   return reverse;
}

When writing code involving linked lists, we must always be careful to properly handle the exceptional cases (when the linked list is empty, when the list has only one or two nodes) and the boundary cases (dealing with the first or last items). This is usually much trickier than handling the normal cases.
Recursive solution : Assuming the linked list has N nodes , we recursively reverse the last N – 1 nodes, and then carefully append the first node to the end.

public Node reverse(Node first)
    {
       if (first == null) return null;
       if (first.next == null) return first;
       Node second = first.next;
       Node rest = reverse(second);
       second.next = first;
       first.next  = null;
       return rest;
}

答案

public class LinkedListExecise8<Item> {

    private static class Node<Item> {
        Node next;
        Item item;

        public String toString() {
            return "item:" + item;
        }
    }
    
    public static Node reverse(Node x){
        Node first = x;
        Node reverse = null;
        while(first != null){
                  Node second = first.next;  
                  first.next = reverse;  
                  reverse = first;  
                  first = second;           
        }
        return reverse;
    }

    public static void main(String[] args) {
        /**
         * 创建链表
         */
        Node<String> first = new Node<String>();
        Node<String> second = new Node<String>();
        Node<String> third = new Node<String>();
        Node<String> forth = new Node<String>();
        Node<String> fifth = new Node<String>();
        first.item = "我的";
        first.next = second;
        second.item = "名字";
        second.next = third;
        third.item = "叫";
        third.next = forth;
        forth.item = "顶级程序员不穿女装";
        forth.next = fifth;
        fifth.item = "微博:https://m.weibo.cn/p/1005056186766482";
        fifth.next = null;
        
        Node newFirst = reverse(first);
        Node current = newFirst;
        while (current != null) {
            System.out.println(current.item);
            current = current.next;
        }
    }
}

代码索引

LinkedListExecise8.java

题目

1.3.31 实现一个嵌套类DoubleNode用来构造双向链表,其中每个结点都含有一个指向前驱元素的引用和一个指向后续元素的引用(如果不存在则为null)。为以下任务实现若干静态方法:在头插入结点、在表尾插入结点、从表头删除结点、从表尾删除结点、在指定结点前插入新结点、在指定结点之后插入新结点、删除指定结点。


1.3.31 Implement a nested class DoubleNode for building doubly-linked lists, where each node contains a reference to the item preceding it and the item following it in the list (null if there is no such item). Then implement static methods for the following tasks: insert at the beginning, insert at the end, remove from the beginning, remove from the end, insert before a given node, insert after a given node, and remove a given node.

广告

我的首款个人开发的APP壁纸宝贝上线了,欢迎大家下载。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,658评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 8,563评论 0 23
  • 杏坛回望意恬恬。正华年,慕先贤,美梦幸得圆。 稚童盈室露欢颜。绘流泉,诵诗篇,鸟雀探窗檐。居教苑,自心安。
    兰泽君阅读 278评论 1 6
  • 19DA以后,大多股票都像犯病了一样,不停盘整,反反复复,感觉整个大盘进入了一阵低迷期。但是,上周一支股票却格外的...
    淘气的络腮胡阅读 263评论 0 0
  • Autumn 秋。 之所以叫秋,是因为我喜欢秋天 一个怀念的季节。 不一定要在布满落叶的林...
    馥徴阅读 241评论 0 0