본문 바로가기

C Language

Linked list를 stack으로 사용하는 예제 | An example for linked list to use as stack

linked list를 스택으로 사용하는 예제

이 코드에서 temp = top->right와 그 이후의 연산들을 단순히 temp = top으로 하지 않는 중요한 이유들은 다음과 같습니다:
스택 구조 보존:
이 함수는 스택의 최상위 노드가 아닌, 그 바로 아래 노드를 제거하도록 설계되었습니다.
temp = top->right는 최상위 바로 아래의 노드를 선택합니다.
적절한 연결 유지:
temp->right->left = top은 제거되는 노드 아래에 있는 노드의 왼쪽 링크를 업데이트하여 최상위 노드와 연결합니다.
top->right = temp->right는 최상위 노드의 오른쪽 링크를 업데이트하여 제거되는 노드를 건너뜁니다.
제거된 노드 분리:
temp->left = NULL과 temp->right = NULL은 제거된 노드를 스택에서 완전히 분리합니다.
이 접근 방식은 다음을 보장합니다:
노드 제거 후에도 스택의 구조가 온전히 유지됩니다.
제거된 노드가 스택에서 완전히 분리됩니다.
남아있는 노드들 간의 연결이 올바르게 업데이트됩니다.
만약 단순히 temp = top을 사용했다면, 최상위 노드 자체를 제거하게 되어 이 함수의 의도된 동작이 아니게 됩니다. 현재의 구현은 최상위에서 두 번째 노드를 제거하면서도 스택 구조의 무결성을 유지할 수 있게 합니다.

 

 

The code temp = top->right and the subsequent operations are used instead of simply temp = top for a few important reasons:
Preserving the stack structure:
This function is designed to remove the second node from the top of the stack, not the top node itself.
temp = top->right selects the node immediately below the top.
Maintaining proper links:
temp->right->left = top updates the left link of the node below the one being removed, connecting it to the top node.
top->right = temp->right updates the top node's right link to skip over the node being removed.
Isolating the removed node:
temp->left = NULL and temp->right = NULL disconnect the removed node from the stack.
This approach ensures that:
The stack's structure remains intact after the removal.
The removed node is completely detached from the stack.
The links between remaining nodes are correctly updated.
If we simply used temp = top, we would be removing the top node itself, which is not the intended behavior of this function. The current implementation allows for the removal of the second node from the top while maintaining the integrity of the stack structure.