이것은 링크 된리스트에 정수를 추가하는 코드입니다.배열 요소를 링크 된리스트에 저장하기
#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)
번호 동적 것이다.
왜 연결 목록이 필요합니까? (증거가 거의 유용하지 않다는 증거가 있음). 정말로 링크 된리스트를 사용해야한다면'std ::: list'를 사용할 수없는 이유가 있을까요? –
이 질문은 주제와는 다른 것으로 보이며 http://codereview.stackexchange.com/에 속합니다. – TemplateRex
@JerryCoffin : 전체 아이디어는 전화 번호 목록을 메모리에 저장하고 가장 빠른 방법으로 원하는 번호를 검색하는 것입니다. – sajal