[英]How to rotate column in grid of doubly linked list
如果我有一個由雙鏈表組成的網格,即每個節點有 4 個指針,左右上下。 我將如何旋轉列,即; 在網格中
A B C D
1 2 3 4
E F G H
節點 D 具有以下指針:left = C right = A up = H 和 down = 4 如何讓網格看起來像:
A B C 4
1 2 3 H
E F G D
在調用 rotate(3,2) function 后,第一個參數是行,第二個是向下旋轉的插槽數。
注意我在 C++ 工作
這聽起來像是編碼面試中的那些技巧問題之一。 您認為必須管理所有這些復雜的指針關系的地方。 但更簡單的解決方案是在列表中的節點之間移動值,並保持節點之間的指針不變。 提示在您自己對問題的描述中(您說“看起來像” )。
因此,在旋轉列的情況下,您可以調用類似於下面的 function 並將該列中的任何項目傳遞給它。
// for each item in the column, copy its value to the item above it
void RotateColumn(Node* firstnode)
{
Node* current = firstnode;
Node* next = current->down;
char firstvalue = current->value;
while (next != firstnode)
{
current->value = next->value;
current = next;
next = next->down;
}
current->value = firstvalue;
}
經過更多思考,我想出了一種不需要任何額外存儲的方法:
N->down
指針 k 次,將結果賦給 N。L->right
到 M 和M->right
到 LR->left
至 M 和M->right
至 R在代碼中,它看起來像這樣:
void rotate_down(Node * N, unsigned int k) {
Node * L = N->left;
Node * R = N->right;
while (k-- > 0) N = N->down;
Node * M = N;
do {
L->right = M; M->left = L;
R->left = M; M->right = R;
L = L->down; M = M->down; R = R->down;
} while (M != N);
}
對於額外的功勞,通過模板參數使這個 function 在移動方向上通用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.