我在尝试用链表来做一道算法题,但是在初始化储存最终答案的链表的时候,可能是设定头节点的下一个节点为空这一句让整个程序出了问题。请求大家帮忙看看是哪里出了错,谢谢~
#include <iostream>
using namespace std;
typedef struct link_node{
int data;
link_node* next;
};
void iter(link_node * head){
link_node* cur = head;
cout<<"The address of head in function: "<<head<<endl;
while(cur!=NULL){
cur = cur->next;
cout<<cur->data<<' ';
}
}
link_node *create(int a){
link_node* head;
link_node* cur;
head =(link_node*) malloc(sizeof(link_node));
cur = head;
for(int i=a;i<a+10;i+=2){
link_node * node = (link_node*) malloc(sizeof(link_node));
node->data = i;
cur->next = node;
cur = node;
}
cur->next = NULL;
// cout<<"address in create: "<<&head<<endl;
return head;
}
link_node* combine_sort(link_node * h1, link_node* h2, link_node* h3){
link_node* cur_1 = h1->next;
link_node* cur_2 = h2->next;
link_node* temp;
while(cur_1 && cur_2){
if(cur_1->data<cur_2->data){
cout<<"here";
// temp = cur_1;
cur_1 = cur_1->next;
// temp->next = h3->next;
// h3->next = temp;
}
else{
cout<<"here2";
// temp = cur_2;
cur_2 = cur_2->next;
// temp->next = h3->next;
// h3->next = temp;
}
}
// if(cur_1 && !cur_2){
// while(cur_1){
// cout<<cur_1->data<<' ';
// cur_1 = cur_1->next;
// }
// }
// else{
// while(cur_2){
// cout<<cur_2->data<<' ';
// cur_2 = cur_2->next;
// }
// }
return result;
}
int main(){
link_node* head_1 = create(0);
link_node* head_2 = create(1);
link_node* result = (link_node*) malloc(sizeof(link_node));
link_node* result = head_1;
result->next = NULL;
combine_sort(head_1,head_2, result);
cout<<"here";
return 0;
}
在main函数中添加"result->next=NULL;" 的话就只会输出一个here。正确的输出应该是输出九个here
数据结构对单链表进行数据排序 http://bbs.csdn.net/topics/392201633