java吧 关注:1,271,436贴子:12,778,441
  • 1回复贴,共1

求大神指点,java设计链表,总是不对

只看楼主收藏回复

707. 设计链表 - 力扣(LeetCode) (leetcode-cn.com)
class MyLinkedList {
int size;
ListNode head; // sentinel node as pseudo-head
private class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; next = null;}
ListNode() {}
}
public MyLinkedList() {
size = 0;
head = new ListNode();
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
public int get(int index) {
if (index < 0 || index >= size){
return -1;
}
ListNode my = head;
for (int i = 0; i < index; i++){
my = my.next;
}
return my.val;
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
public void addAtHead(int val) {
ListNode temp = new ListNode(val);
temp.next = head;
head = temp;
size++;
}
/** Append a node of value val to the last element of the linked list. */
public void addAtTail(int val) {
ListNode add = head;
ListNode temp = new ListNode(val);
for (int i = 0; i < size - 1; i++){
add = add.next;
}
add.next = temp;
size++;
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
public void addAtIndex(int index, int val) {
if (index <= 0){
addAtHead(val);
}
if (index == size){
addAtTail(val);
}
if(index > size){
return;
}
ListNode addAtIndex = head;
ListNode add = new ListNode(val);
for (int i = 0;i < index - 1; i++){
addAtIndex = addAtIndex.next;
}
add.next = addAtIndex.next;
addAtIndex.next = add;
size++;
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void deleteAtIndex(int index) {
if (index < 0 || index >= size){
return;
}
ListNode tr = head;
for (int i = 0;i < (index - 1); i++){
tr = tr.next;
}
tr.next = tr.next.next;
size--;
}
}


IP属地:北京1楼2021-08-20 22:28回复
    https://leetcode-cn.com/problems/design-linked-list/ 这是题目网址


    IP属地:北京2楼2021-08-20 22:32
    回复