2013-07-17 2 views
0

이것은 링크 된리스트에 정수를 추가하는 코드입니다.배열 요소를 링크 된리스트에 저장하기

#include "iostream" 
using namespace std; 

class LinkList 
{ 
private: 
     struct Node 
     { 
     int data; 
     Node* link; 
     }*p; 

public: 
     LinkList(); 
     ~LinkList(); 

     void Print();   // Prints the contents of linkedlist 
     void Append(int num); // Adds a new node at the end of the linkedlist 
     void Delete(int num); // Deletes the specified node from the linkedlist 

     void AddatBeg(int num);// Adds a new node at the beginning of the linkedlist 
     void AddAfter(int c, int num); // Adds a new node after specified number of nodes 
     int Count();   // Counts number of nodes present in the linkedlist 

}; 

LinkList::LinkList() 
{ 
    p = NULL; 
} 

LinkList::~LinkList() 
{ 
    if (p == NULL) 
     return; 

    Node* tmp; 
    while(p != NULL) 
    { 
     tmp = p->link ; 
    delete p; 
     p = tmp; 
    } 
} 

// Prints the contents of linkedlist 
void LinkList::Print() 
{ 
    if (p == NULL) 
    { 
     cout<< "EMPTY"; 
     return; 
    } 

    //Traverse 
    Node* tmp = p; 
    while(tmp != NULL) 
    { 
     cout<<tmp->data<<endl; 
     tmp = tmp->link ; 
    } 
} 

// Adds a new node at the end of the linkedlist 
void LinkList::Append(int num) 
{ 
     Node *newNode; 

     newNode = new Node; 
     newNode->data = num; 
     newNode->link = NULL; 

     if(p == NULL) 
     { 
     //create first node 
     p = newNode; 
     } 
     else 
     { 
      //Traverse 
      Node *tmp = p; 
      while(tmp->link != NULL) 
      { 
        tmp = tmp->link; 
      } 

      //add node to the end 
     tmp->link = newNode; 
     } 
} 

// Deletes the specified node from the linkedlist 
void LinkList::Delete(int num) 
{ 
    Node *tmp; 

    tmp = p; 
    //If node to be delete is first node 
    if(tmp->data == num) 
    { 
     p = tmp->link; 
     delete tmp; 
     return; 
    } 

    // traverse list till the last but one node is reached 
    Node *tmp2 = tmp; 
    while(tmp!=NULL) 
    { 
     if(tmp->data == num) 
     { 
     tmp2->link = tmp->link; 
     delete tmp; 
     return; 
     } 

     tmp2 = tmp; 
     tmp = tmp->link; 
    } 
    cout<< "\nElement "<<num<<" not Found." ; 
} 

int LinkList::Count() 
{ 
     Node *tmp; 
     int c = 0; 

     //Traverse the entire Linked List 
     for (tmp = p; tmp != NULL; tmp = tmp->link) 
      c++; 

     return (c); 
} 

int main() 
{ 
     LinkList* pobj = new LinkList(); 
     pobj->Append(11); 
     pobj->Print(); 

     delete pobj; 
     return 0; 
} 

내가 찾고있는 것은 링크 된 목록에 배열 요소를 삽입 할 수있는 코드입니다. 예를 들어 요소 (1,2,3)와 요소 (4,5,6)를 포함하는 배열이 두 개인 경우 코드는 두 개의 연결된 목록을 만들어야하며 각 연결된 목록의 첫 번째 노드 주소는 배열에 저장해야합니다. for 루프를 실행하면 연결된 모든 목록이 순서대로 인쇄됩니다. 예 : 배열 어레이 및 내부 구성 요소의 수

Linked List 1 = (1,2,3) 
Linked List 2 = (4,5,6) 

번호 동적 것이다.

+1

왜 연결 목록이 필요합니까? (증거가 거의 유용하지 않다는 증거가 있음). 정말로 링크 된리스트를 사용해야한다면'std ::: list'를 사용할 수없는 이유가 있을까요? –

+0

이 질문은 주제와는 다른 것으로 보이며 http://codereview.stackexchange.com/에 속합니다. – TemplateRex

+0

@JerryCoffin : 전체 아이디어는 전화 번호 목록을 메모리에 저장하고 가장 빠른 방법으로 원하는 번호를 검색하는 것입니다. – sajal

답변

2

std::vector< std::vector<int> > vect;

+0

은> 연산자가 >> 연산자 인 후에 공간을 두는 것을 잊지 말고 컴파일 시간 오류 –

+0

@ sajal chk 답 그리고 목록을 포함하는 목록의 크기를 원하기 때문에 이것을 성장시키는 것이 해결책입니다. –

+1

고마워요. 내가 찾던 해결책. – sajal

2

참고 : 귀하의 질문은 학습 목적으로 생각됩니다. 그렇지 않으면 자신의 링크 된 목록을 구현하지 말고 std::vector을 사용하십시오. 벡터를 std::list으로 지정하면 캐시가 누락되어 링크 된 목록의 벡터 성능이 저하됩니다. this question about performance comparisons between std::list and syd::vector을 확인하십시오.

연결리스트 일반적 push_backpop_back 작업 O (1) (즉, 어떤 이송와 push_back 필요하지이다)하기 위해, 이중 연결리스트로 구현된다.

struct node 
{ 
    node* previous; 
    node* next; 
    int data; 
}; 

그리고 연결리스트 클래스 저장 끝을 나타내는 노드 :

이를 구현하는 방법

노드의 다음 노드뿐만 아니라 링크, 이전 노드로도 링크를 저장한다 목록의 시작 노드에 추가 :

node* begin; 
node* end; 

주 내가 말한하지 "목록의 끝을 나타내는 노드" "목록의 마지막 노드". 즉, end->previous은 목록의 마지막 노드를 가리 킵니다. end->next은 (nullptr)을 가리 킵니다. Check this picture.

이러한 방식에 의해, push_back 구현은 삽입 후 end->previous의 값을 가리키는 end->preious 새로운 노드를 가리키는 (및 new_node->nextend 가리키는) 및 new_node->previous을 둔다.

+0

std :: vector를 사용하더라도 모든 벡터를 하나씩 표시하는 벡터 배열을 찾고 있습니다. – sajal

+0

그런 다음 노드의 데이터 멤버를 변경하고 std :: vector를 사용합니다. 하지만 가장 간단한 방법은 벡터 벡터를 사용하는 것입니다 ('std :: vector ') – Manu343726

관련 문제