繁体   English   中英

对指针C的混淆(链接列表)

[英]Confusion on pointers C (Linked list)

我正在尝试交换链表中两个相邻节点的地址。 我尝试使用int temp变量交换它们的值,它完全正常。 但现在,我想通过指针交换两个地址。 不幸的是,它在我的while循环中创建了一个无限循环。 这是我的代码片段:

使用int://工作得很好

node* swapNumbers(node* head, int data){
    int temp;
    node *cursor = head;

    while(cursor!=NULL){
        if(cursor->data == data){
            temp = cursor->data;
            cursor->data = cursor->next->data;
            cursor->next->data = temp;
            //printf("1: %d\n", cursor->data);
            //printf("2: %d\n", cursor->next->data);

            return cursor;      
        } 
        cursor = cursor->next;
    }
    return NULL;
}

使用地址://这创建了一个无限循环!

node* swapNumbers(node* head, int data){
    node *temp = NULL;
    node *cursor = head;

    while(cursor!=NULL){
        if(cursor->data == data){
            temp = cursor;
            cursor = cursor->next;
            cursor->next = temp;
        return cursor;      
        } 
        cursor = cursor->next;
    }
    return NULL;
}

我的typedef结构包含以下内容:

typedef struct node
{
    int data;
    struct node* next;
} node;

我是C的新手,指针仍然让我感到困惑。 任何帮助将不胜感激!

为了不进入无限循环,您需要将cursor的前趋值保存在另一个指针指向的临时值中。

您必须在代码中处理三种情况。

  1. 如果数据节点是第一个节点。 你必须改变头指针。 因为你只传递指针你不能改变其他头是第二个元素。

  2. 如果数据节点是最后一个节点。 你不能交换。

  3. 如果数据节点是中间节点。 您需要先前的光标,因此您可以将其指向正确的节点。 假设您有prev节点

      if(cursor->data == data) { temp = cursor; cursor = cursor->next; if (NULL == cursor) return NULL; temp->next = cursor->next; prev->next = cursor; cursor->next = temp; return cursor; } 

我可以建议一种简单的方法来交换单链表中的两个节点吗?

/* p points to the node before a, a and b are the nodes to be swapped */
void swap_address(node* p, node* a, node* b) 
{
    node* n = b->next; /* save the address of the node after b */

    if (!p || !a || !b)
    {
        printf("One of the arguments is NULL!\n");
        return;
    }

    p->next = b; /* p points to b */
    b->next = a; /* b points to a */
    a->next = n; /* a points to the node that was originally after b */
}

在我的机器上,我尝试使用以下结构定义:

typedef struct node
{
    struct node* next;
    int val;
} node;

我用它是这样的:

swap_address(b, c, d);

我有节head - > a - > b - > c - > d ,其顺序为1,2,3和4。

交换后,订单更改为1 - > 2 - > 4 - > 3。

这就是你追求的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM