// public class List{
// public static void main(String[] args){
// MyLinkedList linkedList = new MyLinkedList();
// linkedList.addAtHead(1);
// linkedList.addAtTail(3);
// linkedList.addAtIndex(1,2); //链表变为1-> 2-> 3
// linkedList.get(1); //返回2
// linkedList.deleteAtIndex(1); //现在链表是1-> 3
// linkedList.get(1); //返回3
// }
// }
class DoubleListNode{
int val;
DoubleListNode next;
DoubleListNode prev;
public DoubleListNode() {
}
public DoubleListNode(int val){
this.val = val;
}
}
class MyLinkedList {
int size;
DoubleListNode head;
DoubleListNode tail;
public MyLinkedList() {
size = 0;
head = new DoubleListNode();
tail = new DoubleListNode();
//这里要注意,初始化的时候,双向链表的头尾是相连的。并且head的prev为null,tail的next为null。
head.next = tail;
tail.prev = head;
}
public int get(int index) {
if(index < 0 || index >=size){
return -1;
}
DoubleListNode cur = new DoubleListNode();
if(index < (size - 1)/2){
cur = head;
//从头开始走到索引为Index的结点处,要走index+1步
for(int i = 0;i < (index+1); i ++){
cur = cur.next;
}
}
if(index >= (size-1)/2){
cur = tail;
//从尾巴开始走,走到索引为index处的结点,要走size-index步
for(int i = 0;i < (size-index);i ++){
cur = cur.prev;
}
}
return cur.val;
}
public void addAtHead(int val) {
size++;
DoubleListNode tooAdd = new DoubleListNode(val);
tooAdd.next = head.next;
head.next.prev = tooAdd;
head.next = tooAdd;
tooAdd.prev = head;
}
public void addAtTail(int val) {
size++;
DoubleListNode tooAdd = new DoubleListNode(val);
tooAdd.prev = tail.prev;
tail.prev.next = tooAdd;
tooAdd.next = tail;
tail.prev = tooAdd;
}
public void addAtIndex(int index, int val) {
if(index > size){
return;
}
DoubleListNode tooAdd = new DoubleListNode(val);
DoubleListNode before = head;
size ++;
if(index < 0){
index = 0;
}
for(int i = 0;i < index ; i ++){
before = before.next;
}
tooAdd.next = before.next;
before.next.prev = tooAdd;
before.next = tooAdd;
tooAdd.prev = before;
}
public void deleteAtIndex(int index) {
if(index < 0 || index >= size){
return;
}
DoubleListNode before = head;
size --;
for(int i = 0;i < index ; i ++){
before = before.next;
}
before.next.next.prev = before;
before.next = before.next.next;
}
}
// //这里要注意,初始化的时候,双向链表的头尾是相连的。并且head的prev为null,tail的next为null。
// head.next = tail;
// tail.prev = head;
//注意依靠next指针寻找到的结点要放到最后面去交换。
// tooAdd.next = before.next;
// before.next.prev = tooAdd;
// before.next = tooAdd;
// tooAdd.prev = before;
// //从头开始走到索引为Index的结点处,要走index+1步
// for(int i = 0;i < (index+1); i ++){
// //从尾巴开始走,走到索引为index处的结点,要走size-index步
// for(int i = 0;i < (size-index);i ++){
双链表的设计
最新推荐文章于 2023-04-07 16:29:36 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)