如何解决我想知道这段代码中的* list指针是什么
此代码是关于交换单链列表的两个节点。 * list变量仅在这两个函数中,甚至在main函数中。我尚未定义* list指针变量是什么,但是此代码仍然有效。为什么行得通,为什么当除了两个函数之外* list变量没有其他地方时我们将* list参数传递给这些函数,以及值列表指针会得到什么,以及为什么要解释呢。
'''
int main()
{
int n,pos1,pos2;
// Input node count to create
printf("Enter number of node to create: ");
scanf("%d",&n);
createList(n);
// Display list
printf("\n\nData in list before swapping: \n");
displayList();
printf("\nEnter first node position to swap: ");
scanf("%d",&pos1);
printf("\nEnter second node position to swap: ");
scanf("%d",&pos2);
if (swap(head,pos2) == 1)
{
printf("\nData swapped successfully.\n");
printf("Data in list after swapping %d node with %d: \n",pos2);
displayList();
}
else
{
printf("Invalid position,please enter position greater than 0 and less than nodes in list.\n");
}
return 0;
}
/**
* Counts total number of nodes in a linked list.
* @param *list Pointer to head node of linked list.
* @returns Total count of nodes in list.
*/
int count(struct node *list)
{
int nodes = 0;
while (list != NULL)
{
nodes++;
list = list->next;
}
return nodes;
}
int swap(struct node *list,int pos1,int pos2){
struct node *node1,*node2,*prev1,*prev2,*temp;
int i;
//get the far postion among both
const int maxpos = (pos1 > pos2) ? pos1 : pos2;
//get total in the list
const int totalnodes = count(list);
//validate swap positions
if((pos1 <= 0 || pos1 > totalnodes) || (pos2 <= 0 || pos2 > totalnodes)){
return -1;
}
//if both position are same then no swapping required
if(pos1 == pos2){
return 1;
}
//identify both nodes to swap
i = 1;
temp = list;
}
'''
解决方法
在main()
和要调用的函数中,要传递的变量的名称可以不同。这是一个简单的例子。
int foo(int a,int b)
{
return a+b;
}
int main()
{
int c=5,RandomVar=6,sum;
sum = foo(c,RandomVar);
printf("%d",sum);
return 0;
}
在上述情况下,当调用foo()
时,a
等于c
,而b
等于RnadonVar
。
现在,在您的情况下,*list
是一个指针,用于将整个链接“列表”传递给链接列表的head
所标识的函数。
您使用head
遍历链接列表。这样一来,根据您的情况,列表的'swap()function can traverse link list,it is having the
* list being passed to it which is the
头就会出现。
此功能:
int swap(struct node *list,int pos1,int pos2){
声称它返回一个int
。但是,该函数包含一个在函数末尾运行的执行路径,而不会返回任何内容
关于
struct node *node1,*node2,*prev1,*prev2,*temp;
上一行中唯一使用的变量是:*temp
建议将该行替换为;
struct node *temp;
但是,此变量仅设置而未使用。
关于;
int i;
已设置此i
变量,但从未使用过。
关于;
const int maxpos = (pos1 > pos2) ? pos1 : pos2;
从不使用const maxpos
。建议取消此行
在发布的代码中的任何地方都没有定义struct node
函数中变量的名称仅作用于函数本身。因此,变量*list
仅在函数本身内被调用。但是,当您调用swap
函数时,您正在传递一个内存引用,该引用在函数本身内仅称为*list
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。