本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本人新建了一个微信群(算法交流),想要加入的,请添加我的微信号:zhujinhui207407 谢谢。另外,本人的个人博客 http://www.kyson.cn 也在不停的更新中,欢迎一起讨论
知识点
- 链表节点增删查改
题目
1.3.21 编写一个方法find(),接受一条链表和一个字符串key作为参数。如果链表中的某个结点的item域的值为key,则方法返回true,否则返回false。
1.3.21 Write a method find() that takes a linked list and a string key as arguments and returns true if some node in the list has key as its item field, false otherwise.
答案
public class LinkedListExecise3 {
private static class Node {
Node next;
String item;
}
public boolean find(Node first, String key) {
if (first == null)
return false;
Node current = first;
while (current != null) {
if (current.item.equals(key)) {
return true;
}
current = current.next;
}
return false;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* 创建链表
* */
Node first = new Node();
Node second = new Node();
Node third = new Node();
Node forth = new Node();
Node fifth = new Node();
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;
String targetString = "微博:https://m.weibo.cn/p/1005056186766482";
LinkedListExecise3 linkedListExecise3 = new LinkedListExecise3();
boolean find = linkedListExecise3.find(first, targetString);
System.out.println("查找字符串" + targetString + ":" + find);
}
代码索引
题目
1.3.22 假设x是一条链表中的某个结点,下面这段代码做了什么?
t.next = x.next;
x.next = t;
答案:将节点t插入到结点x后面。
**1.3.22 Suppose that x is a linkedlist Node.What does the following code fragment do? **
t.next = x.next;
x.next = t;
Answer : Inserts node t immediately after node x.
题目
1.3.23 为什么下面这段代码和上一道题中的代码效果不同?
x.next = t;
t.next = x.next;
在更新t.next时,x.next已经不再指向x的原来后续结点,而是指向t本身。
1.3.23 Why does the following code fragment not do the same thing as in the previous question?
x.next = t;
t.next = x.next;
Answer : When it comes time to update t.next, x.next is no longer the original node following x, but is instead t itself!
广告
我的首款个人开发的APP壁纸宝贝上线了,欢迎大家下载。
网友评论