프로그래밍/자료구조
링크드리스트 순차탐색
lee ho jun
2016. 3. 7. 14:45
반응형
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | #include <iostream> using namespace std; // Node 구조체 typedef struct node{ struct node *Next; int data; char ch; }Node; // Node 생성 Node* create(int Data , char Ch) { Node *newNode = (Node*)malloc(sizeof(Node)); newNode->data = Data; newNode->Next = NULL; newNode->ch = Ch; return newNode; } // Node 추가 void addNode(Node **Head , Node* NewNode) { if((*Head) == NULL) (*Head) = NewNode; else { Node *tmp = (*Head); while(tmp->Next !=NULL) tmp = tmp->Next; tmp->Next = NewNode; } } // 모든 Node 출력 void printNode(Node *Head) { while(Head!= NULL) { cout<<Head->data; Head = Head->Next; } } // 탐색 Node* Search(Node* Head , int Data) { Node *Match = NULL; while(Head !=NULL) { if(Head->data == Data) { Match = Head; break; } Head = Head->Next; } return Match; } int main() { Node* Head=NULL; Node* a; Node* b; Node* c; Node* d; Node* ser = NULL; // Node 생성 a = create(1,'a'); b = create(2,'b'); c = create(3,'c'); d = create(4,'d'); // Node 추가 addNode(&Head , a); addNode(&Head , b); addNode(&Head , c); addNode(&Head , d); // 3이라는 Data를 가지는 Node 검색 ser = Search(Head , 3); // 해당 Node가 맞는지 출력 cout<<ser->ch<<endl; return 0; } | cs |
이전에 보았던 링크드 리스트에서 해당 Node가 가지는 Data값을 탐색하고 해당 Node의 주소를 반환하는 Search 함수를 만들어 보았다.
위의 소스에서 3이라는 Data를 가지는 Node를 찾으려고 했으며 예상 되는 결과값은 'c'이다.
결과
반응형