站在Java的角度看,玩队列不就是玩对象引用对象嘛!
- public class LinkedList<E> implements List<E>, Deque<E> {
- Node<E> first;
- Node<E> last;
- int size;
- public boolean add(E e) {
- final Node<E> l = last;
- final Node<E> newNode = new Node<>(l, e, null);
- last = newNode;
- if (l == null)
- first = newNode;
- else
- l.next = newNode;
- size++;
- modCount++;
- return true;
- }
- private static class Node<E> {
- E item;
- Node<E> next;
- Node<E> prev;
- Node(Node<E> prev, E element, Node<E> next) {
- this.item = element;
- this.next = next;
- this.prev = prev;
- }
- }
- }
单链表反转:
- /**
- * 递归,在反转当前节点之前先反转后续节点
- */
- public static Node reverse(Node head) {
- if (null == head || null == head.getNextNode()) {
- return head;
- }
- Node reversedHead = reverse(head.getNextNode());
- head.getNextNode().setNextNode(head);
- head.setNextNode(null);
- return reversedHead;
- }
- /**
- * 遍历,将当前节点的下一个节点缓存后更改当前节点指针
- *
- */
- public static Node reverse2(Node head) {
- if (null == head) {
- return head;
- }
- Node pre = head;
- Node cur = head.getNextNode();
- Node next;
- while (null != cur) {
- next = cur.getNextNode();
- cur.setNextNode(pre);
- pre = cur;
- cur = next;
- }
- //将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head
- head.setNextNode(null);
- head = pre;
- return head;
- }
对于数组问题,一般我们要新建数组,必要时移动下标
原文链接:[http://wely.iteye.com/blog/2326330]
时间: 2024-10-21 18:28:13