C 移位插入链表
C shift insert linked list
我想在这个函数的根的开头插入:
struct elem {
int value;
struct elem *next;
};
typedef struct elem Node;
void shiftInsert(Node *n, int v){
int tmp;
while (n != NULL){
n = n->next;
}
}
当 Node *n
是:
1 -> 2 -> 3 -> 4 -> 5
并致电 shiftInsert(88)
Node *n
的输出需要是:
88->1 -> 2 -> 3 -> 4
我怎样才能做到这一点?
貌似shiftInsert
是设计在链表开头插入一个值,然后push第一个节点的(前) 值到下一个节点, 重复,直到最后一个值已 "shifted" 关闭。我会尝试类似的东西:
void shiftInsert(Node *n, int v) {
Node *iterator = n;
int tmpPrev = v;
int tmpCurr = 0;
while(iterator != NULL) {
//save the current value
tmpCurr = iterator->value;
//set the new value
iterator->value = tmpPrev;
//save the old value
tmpPrev = tmpCurr;
//next node
iterator = iterator->next;
}
}
我想在这个函数的根的开头插入:
struct elem {
int value;
struct elem *next;
};
typedef struct elem Node;
void shiftInsert(Node *n, int v){
int tmp;
while (n != NULL){
n = n->next;
}
}
当 Node *n
是:
1 -> 2 -> 3 -> 4 -> 5
并致电 shiftInsert(88)
Node *n
的输出需要是:
88->1 -> 2 -> 3 -> 4
我怎样才能做到这一点?
貌似shiftInsert
是设计在链表开头插入一个值,然后push第一个节点的(前) 值到下一个节点, 重复,直到最后一个值已 "shifted" 关闭。我会尝试类似的东西:
void shiftInsert(Node *n, int v) {
Node *iterator = n;
int tmpPrev = v;
int tmpCurr = 0;
while(iterator != NULL) {
//save the current value
tmpCurr = iterator->value;
//set the new value
iterator->value = tmpPrev;
//save the old value
tmpPrev = tmpCurr;
//next node
iterator = iterator->next;
}
}