[英]How to retrieve array from void function and pass to other functions in Main?
[英]how to get the LinkedList address from other void functions
我想反轉鏈表以將頭指針參數提供給 reverse2 function。
我希望 reverse2 function 反轉鏈表並將地址替換為頭指針
//linked list//
typedef struct node* lsnode;
typedef struct node
{
int data;
lsnode link;
}node;
//create the 3 nodes
lsnode create3()
{
lsnode first, second, last;
first = (lsnode)malloc(sizeof(node));
second = (lsnode)malloc(sizeof(node));
last = (lsnode)malloc(sizeof(node));
first->data = 30;
first->link = second;
second->data = 20;
second->link = last;
last->data = 10;
last->link = NULL;
return first;
}
//reverse the linkedlist
void reverse2(lsnode head)
{
lsnode q,p,r;
p = head;
q = NULL;
r = NULL;
while (p != NULL)
{
r = q;
q = p;
p = p->link;
q->link = r;
}
head = p;
}
int main(void)
{
lsnode head = create3();
reverse2(head);
while (head)
{
printf("%d\n", head->data);
head = head->link;
}
return 0;
}
該程序只打印 30 但是,我想打印 10 20 30 我的代碼有什么問題..
根據評論中的一些建議,以下修改reverse2
function 以傳遞正在更改的 object 的地址,而不是 object 本身,允許修改后的 object 在其返回時在調用 function 中被引用。 關於@Some programmer dude 關於可視化價值的建議,我發現這很有幫助。
此外,為了使代碼更易於理解,此代碼將單字母變量名稱擴展為符號,任何閱讀代碼的人都可以更輕松地理解這些符號。
typedef struct node* lsnode;
typedef struct node
{
int data;
lsnode next;//changed from link
}node;
//create the 3 nodes
lsnode create3()
{
lsnode first, second, last;
first = (lsnode)malloc(sizeof(node));
second = (lsnode)malloc(sizeof(node));
last = (lsnode)malloc(sizeof(node));
first->data = 30;
first->next = second;
second->data = 20;
second->next = last;
last->data = 10;
last->next = NULL;
return first;
}
//reverse the linkedlist
void reverse2(lsnode *head)//changed prototype,
{
//lsnode q,p,r;
lsnode prev,current,next;//note these changes throughout
current = *head;//note use of asterisk to reference
//object being changed
prev = NULL;
next = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
int main(void)
{
lsnode head = create3();
reverse2(&head);//passes address of object to be modified
while (head)
{
printf("%d\n", head->data);
head = head->next;
}
return 0;
}
輸出:
10
20
30
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.