首页 > 解决方案 > 我想知道这个 *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;
}

'''

标签: cdata-structureslinked-listswapsingly-linked-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 thehead”。


推荐阅读