×

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

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

### 题目

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) {
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);
}
}
``````

### 题目

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;
}
}
}
``````