c - 我想知道这个 *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, pos1, pos2) == 1)
{
printf("\nData swapped successfully.\n");
printf("Data in list after swapping %d node with %d: \n", pos1, 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
head”。
推荐阅读
- c# - 如何通过单击按钮在 Windows 窗体应用程序中停止执行操作?
- scala - 面临 sbt 依赖的问题
- javascript - 如何从脚本中的 ID 转换为调用类?
- javascript - 自定义组件中的@input 事件
- mysql - 如何创建触发器以删除几乎重复的 lat 值
- firebase - 我可以将firebase用于文本短信,例如短信营销而不是身份验证
- javascript - Firebase 数据库查询打印数据库信息,而不是数据
- javascript - 如何向我的网站添加加载动画?
- postgresql - 如何提交 PostgreSQL 中处于空闲状态的事务?
- swift - 如何在 UIView 中为表格视图标题部分绘制自定义形状?