java LinkedList的实例详解
程序员文章站
2024-02-24 09:28:55
java linkedlist的实例详解
站在java的角度看,玩队列不就是玩对象引用对象嘛!
实例代码:
public class linked...
java linkedlist的实例详解
站在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; }
对于数组问题,一般我们要新建数组,必要时移动下标
以上就是java linkedlist 的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!