【发布时间】:2014-01-21 00:42:12
【问题描述】:
我用 C++ 编写了一个函数,可以很好地在单链表中成对交换元素。但是,我想知道是否有更有效的方法来做同样的事情。具体来说,我编写的函数有一个案例,它处理链表中只有两个元素的情况。我想知道这种情况是否可以省略并放在一般情况下。我尝试这样做,但未能获得输出。是否可以?这是我的代码 sn-p...
struct Node* swap(struct Node* head){
struct Node* temp = NULL;
struct Node* cur;
struct Node* next;
cur = head;
next = cur->next;
// Empty list.
if(head == NULL){
cout<<"List is empty. \n";
return NULL;
}
// Only one element in the list.
if(next == NULL){
return cur;
}
// If two elements in the list.
else if(next->next == NULL){
cur->next = NULL;
next->next = cur;
return next;
}
// General case.
else{
head = next;
while(cur!=NULL){
if(next == NULL)
break;
if(next->next == NULL)
break;
cur->next = next->next;
next->next = cur;
if(temp == NULL)
temp = cur;
else{
temp->next = next;
temp = cur;
}
cur = cur->next;
next = cur->next;
}
return head;
}
}
【问题讨论】: