mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
update problem 707 java version solution
This commit is contained in:
@ -328,14 +328,29 @@ class MyLinkedList {
|
||||
return currentNode.val;
|
||||
}
|
||||
|
||||
//在链表最前面插入一个节点,等价于在第0个元素前添加
|
||||
public void addAtHead(int val) {
|
||||
addAtIndex(0, val);
|
||||
ListNode newNode = new ListNode(val);
|
||||
newNode.next = head.next;
|
||||
head.next = newNode;
|
||||
size++;
|
||||
|
||||
// 在链表最前面插入一个节点,等价于在第0个元素前添加
|
||||
// addAtIndex(0, val);
|
||||
}
|
||||
|
||||
//在链表的最后插入一个节点,等价于在(末尾+1)个元素前添加
|
||||
|
||||
public void addAtTail(int val) {
|
||||
addAtIndex(size, val);
|
||||
ListNode newNode = new ListNode(val);
|
||||
ListNode cur = head;
|
||||
while (cur.next != null) {
|
||||
cur = cur.next;
|
||||
}
|
||||
|
||||
cur.next = newNode;
|
||||
size++;
|
||||
|
||||
// 在链表的最后插入一个节点,等价于在(末尾+1)个元素前添加
|
||||
// addAtIndex(size, val);
|
||||
}
|
||||
|
||||
// 在第 index 个节点之前插入一个新节点,例如index为0,那么新插入的节点为链表的新头节点。
|
||||
@ -407,7 +422,7 @@ class MyLinkedList {
|
||||
|
||||
public int get(int index) {
|
||||
//判断index是否有效
|
||||
if(index<0 || index>=size){
|
||||
if(index>=size){
|
||||
return -1;
|
||||
}
|
||||
ListNode cur = this.head;
|
||||
@ -441,10 +456,7 @@ class MyLinkedList {
|
||||
if(index>size){
|
||||
return;
|
||||
}
|
||||
//index小于0
|
||||
if(index<0){
|
||||
index = 0;
|
||||
}
|
||||
|
||||
size++;
|
||||
//找到前驱
|
||||
ListNode pre = this.head;
|
||||
@ -462,7 +474,7 @@ class MyLinkedList {
|
||||
|
||||
public void deleteAtIndex(int index) {
|
||||
//判断索引是否有效
|
||||
if(index<0 || index>=size){
|
||||
if(index>=size){
|
||||
return;
|
||||
}
|
||||
//删除操作
|
||||
|
Reference in New Issue
Block a user