我已经在C语言中实现了一个简单的链表,但是可以在不使用双指针(**)的情况下实现。我想通过仅使用单指针来实现相同的程序。
override func didMoveToView(view:SKView) {
let wait = SKAction.waitForDuration(0.1)
let block1 = SKAction.runBlock({
updateSegment1()
})
let block2 = SKAction.runBlock({
updateSegment2()
})
let block3 = SKAction.runBlock({
updateSegment3()
})
let sequence = SKAction.sequence([wait,block1,wait,block2,wait,block3])
self.runAction(SKAction.repeatActionForever(sequence), withKey:"timer")
// Use the following to terminate the timer
//self.removeActionForKey("timer")
}
是否可以替换" struct node ** head_ref"使用" struct node * head_ref"?
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void push(struct node** head_ref, int new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void append(struct node** head_ref, int new_data)
{
struct node* new_node = (struct node*) malloc(sizeof(struct node));
struct node *last = *head_ref; /* used in step 5*/
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
void printList(struct node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}
int main()
{
struct node* head = NULL;
append(&head, 6);
push(&head, 7);
push(&head, 1);
append(&head, 4);
printf("\n Created Linked list is: ");
printList(head);
getchar();
return 0;
}
答案 0 :(得分:3)
是的,您可以仅使用单个指针重写此代码,但您必须更改API的语义及其使用模式。
基本上,你在
中替换第二级间接void push(struct node** head_ref, int new_data)
带有客户端分配,即
struct node* push(struct node* head, int new_data)
这意味着代替
push(&head, num);
来电者必须写
head = push(head, num);
同样适用于append
。
答案 1 :(得分:2)
用(head,6)替换(&amp; head,6)。由于你没有传递头部的地址,在接收端你有push(struct node * head,int new_data).Rest都已经澄清了通过以上给出的答案
答案 2 :(得分:1)
另一种解决方案是创建一个名为head
的空节点,然后创建一个指向该节点的指针list
。然后,您可以将list
传递给所有函数,例如
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void push(struct node *list, int new_data)
{
struct node* new_node = malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = list->next;
list->next = new_node;
}
void append(struct node *list, int new_data)
{
while ( list->next != NULL )
list = list->next;
push( list, new_data );
}
void printList(struct node *node)
{
for ( node=node->next; node != NULL; node=node->next )
printf(" %d ", node->data);
printf( "\n" );
}
int main( void )
{
struct node head = { 0, NULL };
struct node *list = &head;
append(list, 6);
push(list, 7);
push(list, 1);
append(list, 4);
printf("\n Created Linked list is: ");
printList(list);
getchar();
return 0;
}