bre*_*ett 1 c c++ data-structures
我在链接列表中交换相邻节点时遇到问题.
例如:输入:1-> 2-> 3-> 4-> 5->空输出:2-> 1-> 4-> 3-> 5-> null
bool swapAdjacent(node** head)
{
//1->2->3->4->null
//2->1->4->3->null
if(head==NULL)
return 0;
node* current = *head;
*head = (*head)->next ;
node* prev = NULL;
cout<<"head val "<<(*head)->data <<endl;
node* temp;
while( current!=NULL&¤t->next!=NULL)
{
temp = current->next ; //1s pointer points to 2
current->next = temp->next ; // 1s pointer point to 3
temp ->next = current; //2s pointer shud point to 1
prev = current;
current = current->next ;
//cout<<"data " <<current->data <<endl;
if(current!=NULL)
prev->next = current->next ;
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
只要奇数没有节点,我的代码就无法工作.如何解决这个问题?
为什么这么复杂?
int swapAdjacent(node** head) {
if (!*head || !(*head)->next)
return 0;
node* const sw = (*head)->next;
(*head)->next = sw->next;
sw->next = *head;
*head = sw;
swapAdjacent(&(sw->next->next));
return 1;
}
Run Code Online (Sandbox Code Playgroud)
编辑:更改返回值.