Design Linked List

2021. 6. 29. 21:01· 자료구조 알고리즘/코딩테스트
목차
  1. 707. Design Linked List

707. Design Linked List

https://leetcode.com/problems/design-linked-list/

 

Design Linked List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

Language: C++

https://leetcode.com/explore/learn/card/linked-list/209/singly-linked-list/1298/

// Definition for singly-linked list.
struct SinglyListNode {
    int val;
    SinglyListNode *next;
    SinglyListNode(int x) : val(x), next(NULL) {}
};

class MyLinkedList {
private:
    SinglyListNode *head;
public:
    /** Initialize your data structure here. */
    MyLinkedList() {
        head = NULL;
    }
};

/** Helper function to return the index-th node in the linked list. */
SinglyListNode* getNode(int index) {
    SinglyListNode *cur = head;
    for (int i = 0; i < index && cur; ++i) {
        cur = cur->next;
    }
    return cur;
}
/** Helper function to return the last node in the linked list. */
SinglyListNode* getTail() {
    SinglyListNode *cur = head;
    while (cur && cur->next) {
        cur = cur->next;
    }
    return cur;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
    SinglyListNode *cur = getNode(index);
    return cur == NULL ? -1 : cur->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. */
void addAtHead(int val) {
    SinglyListNode *cur = new SinglyListNode(val);
    cur->next = head;
    head = cur;
    return;
}

/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
    if (head == NULL) {
        addAtHead(val);
        return;
    }
    SinglyListNode *prev = getTail();
    SinglyListNode *cur = new SinglyListNode(val);
    prev->next = cur;
}

/** 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. */
void addAtIndex(int index, int val) {
    if (index == 0) {
        addAtHead(val);
        return;
    }
    SinglyListNode *prev = getNode(index - 1);
    if (prev == NULL) {
        return;
    }
    SinglyListNode *cur = new SinglyListNode(val);
    SinglyListNode *next = prev->next;
    cur->next = next;
    prev->next = cur;
}

/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
    SinglyListNode *cur = getNode(index);
    if (cur == NULL) {
        return;
    }
    SinglyListNode *prev = getNode(index - 1);
    SinglyListNode *next = cur->next;
    if (prev) {
        prev->next = next;
    } else {
        // modify head when deleting the first node.
        head = next;
    }
}

다른 solution

class MyLinkedList {

    
public:
    /** Initialize your data structure here. */
    
    class Node {
    public:
        int val;
        Node* next;
        
        Node(int val) {
            this->val = val;
            this->next = NULL;
        }
    };
    
    int length;
    Node* head;
    MyLinkedList() {
        length = 0;
        head = NULL;
    }
    
    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    int get(int index) {
        if (index < 0)
            return -1;
        int i = 0;
        Node* node = head;
        while (i < index) {
            node = node->next;
            i++;
        }
        if (node)
            return node->val;
        else
            return -1;
    }
    
    /** 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. */
    void addAtHead(int val) {
        addAtIndex(0, val);
    }
    
    /** Append a node of value val to the last element of the linked list. */
    void addAtTail(int val) {
        addAtIndex(length, val);
    }
    
    /** 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. */
    void addAtIndex(int index, int val) {
        
        if (index < 0 || index > length)
            return ;
        
        Node* node = head;
        Node* newNode = new Node(val);
        
        if (index == 0) {
            if (!node)
                head = newNode;
            else {
                newNode->next = head;
                head = newNode;
            }
        } else if (index == length) {
            if (!node)
                head = newNode;
            else {
                while (node->next) { 
                    node = node->next;
                }
                node->next = newNode;
            }
            
        } else {
            int i = 1; // 0
            while (i != index) { // i < index - 1
                node = node->next;
                i++;
            }
            
            newNode->next = node->next;
            node->next = newNode;
        }
        
        length++;
    }
    
    /** Delete the index-th node in the linked list, if the index is valid. */
    void deleteAtIndex(int index) {
        
        if (index < 0 || index >= length)
            return ;
        
        Node* node = head;
        if (index == 0) {
            head = head->next;
            node->next = nullptr;
        }
        else {
            int i = 1;
        
            while (i != index) {
                node = node->next;
                i++;
            }
            // prev->next = node->next;
            node->next = node->next->next;
        }
        
        length--;
    }
};

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList* obj = new MyLinkedList();
 * int param_1 = obj->get(index);
 * obj->addAtHead(val);
 * obj->addAtTail(val);
 * obj->addAtIndex(index,val);
 * obj->deleteAtIndex(index);
 */

 

문제점

복잡하게 짜고 싶지 않았었다; 계속 새벽 5시에 자고 계절학기까지 들으니까,, (열심히 듣지는 않지만 ㅎㅎ 내 피 같은 돈..) 

집중 안되서 대충 마무리했었는데 좀 더 쉽고 깔끔하게 다시 도전해보고 싶은 문제.... 문제 수준도 아니다만ㅠㅠㅠㅠㅠ

728x90
반응형

'자료구조 알고리즘 > 코딩테스트' 카테고리의 다른 글

Linked List Cycle II  (0) 2021.07.01
Linked List Cycle  (0) 2021.06.29
Serialize and Deserialize Binary Tree  (0) 2021.06.27
Lowest Common Ancestor of a Binary Tree  (0) 2021.06.26
Populating Next Right Pointers in Each Node II  (0) 2021.06.25
  1. 707. Design Linked List
'자료구조 알고리즘/코딩테스트' 카테고리의 다른 글
  • Linked List Cycle II
  • Linked List Cycle
  • Serialize and Deserialize Binary Tree
  • Lowest Common Ancestor of a Binary Tree
내공얌냠
내공얌냠
내공냠냠
내공얌냠
내공냠냠
내공얌냠
전체
오늘
어제
  • 분류 전체보기 (254)
    • 개발 (113)
      • mediapipe (16)
      • insightface (5)
      • JongjuAR (3)
    • 자료구조 알고리즘 (79)
      • 코딩테스트 (64)
      • 이론 (15)
    • 공부 (7)
      • 단행본 (7)
      • 튜토리얼 (19)
      • 논문 (15)
      • 복기 (5)
    • 참여 (5)

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • flutter 행사
  • postgresql install in mac
  • python telegrambot
  • vscode 스프링 설치
  • 음성인식 기초
  • ios google places api
  • google mediapipe
  • kubeflow설치가이드
  • mediapipe
  • 플러터
  • 컴퓨터 비전
  • 음성인식 튜토리얼
  • 머신러닝이란
  • kubeflow설치안됨
  • git tutorial
  • 미디어파이프
  • torchscript vs onnx vs tensorrt
  • 구글 미디어파이프
  • postgresql 재설치
  • 깃 튜토리얼
  • flutter tutorial
  • mediapipe translate
  • 컴퓨터 비전 책 추천
  • 컴퓨터 비전 기초
  • 딥러닝 기반 음성인식 기초
  • speaker adaptation tts
  • flutter 행사 후기
  • 플러터 튜토리얼
  • flutter
  • flutter conference

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
내공얌냠
Design Linked List
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.