链表应用

链表实现栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class LinkedListStack<E> implements Stack<E> {

private LinkList<E> list;
public LinkedListStack() {
list = new LinkList<>();
}
@Override
public void push(E e) {
list.addFirst(e);
}

@Override
public E pop() {
return list.removeFirst();
}

@Override
public E peek() {
return list.getFirst();
}

@Override
public int getSize() {
return list.getSize();
}

@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public String toString() {
StringBuilder res = new StringBuilder();
res.append("Stack:top");
res.append(list);
return res.toString();
}
}

链表实现队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class LinkedListQueue<E> implements Queue<E> {
private class Node {
public E e;
public Node next;

public Node(E e,Node next) {
this.e = e;
this.next = next;
}

public Node(E e) {
this(e,null);
}
public Node() {
this(null,null);
}
public String toString() {
return e.toString();
}
}

private Node head, tail;
private int size;

public LinkedListQueue() {
head = null;
tail = null;
size = 0;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void enqueue(E e) {
if(tail == null) {
tail = new Node(e);
head = tail;
} else {
tail.next = new Node(e);
tail = tail.next;
}
size ++;
}
public void dequeue() {
if(isEmpty()) {
throw new IllegalArgumentException("Cannot dequeue from an empty queue");
}
Node reNode = head;
head = head.next;
retNode.next = null;
if(head == null) {
tail = null;
}
size --;
return retNode.e;
}
}

链表与递归

移除链表元素
删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {

public ListNode removeElements(ListNode head, int val) {
// 创建虚拟节点
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
for(ListNode pre = dummyHead; pre.next != null;) {
if(pre.next.val == val) {
pre.next = pre.next.next;
} else {
pre = pre.next;
}
}
}
}

把递归过程想成一个子函数,在子函数中写处理逻辑来解决上层函数的问题。

1
2
3
4
5
6
7
8
9
10
public class Solution {

public ListNode removeElements(ListNode head, int val) {
if(head == null){
return null;
}
head.next = removeElements(head.next,val);
return head.val == val? head.next: head;
}
}
-------------本文结束感谢您的阅读-------------