【发布时间】:2013-07-07 03:45:19
【问题描述】:
我正在尝试交换链表中两个相邻节点的地址。 我尝试使用 int temp 变量交换它们的值,并且效果很好。 但是现在,我想通过指针交换两个地址。不幸的是,它在我的 while 循环中创建了一个无限循环。这是我的代码 sn-p:
使用 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 新手,指针仍然让我感到困惑。任何帮助将不胜感激!
【问题讨论】:
-
画图——用线条和箭头表示下一个指针。为了反转链表中的两个节点,您必须更改 previous 节点中的指针(如果没有前一个节点,则更改链表头),以及交换的两个节点。跨度>
-
你在这里找到答案:Swap nodes in a singly-linked list
标签: c list pointers linked-list