[자료구조]Linked List 구현

후이재·2020년 10월 28일
1

Linked List

  • 필기시험을 준비하며, C++의 기본을 다지고자 Linked List를 새로 작성해봤다.
  • 포스팅 된게 없어서 올린다.
#include <iostream>
using namespace std;

class Node
{
    Node * nextN;
    int key;
public:
    Node(){}
    Node(int key): key(key) {}
    
    void setNext(Node * n){
        nextN = n;
    }
    Node* getNext(){
        return nextN;
    }
    int getKey(){
        return key;
    }
};
class LinkedList
{
private:
    Node* head;
    Node* tail;
public:
    LinkedList(){
        head = new Node();
        tail = new Node();
        head->setNext(tail);
        tail->setNext(tail);
    }
    ~LinkedList(){
        deleteAll();
        delete head;
        delete tail;
    }
    
    void insert(const int key){ // 추가
        Node* temp = new Node(key);
        temp->setNext(head->getNext());
        head->setNext(temp);
    }
    void showList(){ // 리스트 출력
        Node* temp = head->getNext();
        while(temp != tail){
            cout<<temp->getKey()<<" ";
            temp = temp->getNext();
        }
        cout<<endl;
    }
    Node* findKey(int key){ // 검색
        Node* temp = head->getNext();
        while(temp->getKey() != key && temp != tail){
            temp = temp->getNext();
        }
        if(temp != tail)
            cout<<"Find "<<key<<endl;
        else
            cout<<"Can't find "<<key<<endl;
        return temp;
    }
    void deleteKey(int key){ // 선택 삭제
        Node* prev = head;
        Node* temp = head->getNext();
        while(temp->getKey() != key && temp != tail){
            prev = temp;
            temp = temp->getNext();
        }
        if(temp!= tail){
            prev->setNext(temp->getNext());
            delete temp;
            cout<<"Delete "<<key<<endl;
        }
    }
    void deleteAll(){ // 전체 삭제
        Node* temp = head->getNext();
        while(temp != tail){
            Node* del = temp;
            temp = temp->getNext();
            delete del;
        }
        head->setNext(tail);
    }
};


int main(){
    cin.tie(0);cout.tie(0);ios::sync_with_stdio(0);
    LinkedList LL = LinkedList();
  
    LL.insert(10);
    LL.insert(20);
    LL.showList();
    LL.insert(33);
    LL.showList();
    LL.findKey(20);
    LL.findKey(50);
    LL.deleteKey(20);
    LL.showList();
    LL.deleteAll();
    LL.showList();
    return 0;
}
profile
공부를 위한 벨로그

0개의 댓글