歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 數據結構學習---有序鏈表的合並

數據結構學習---有序鏈表的合並

日期:2017/3/1 9:17:08   编辑:Linux編程

遞歸調用 簡單

有點像歸並排序的合並部分吧。

因為是用vs創建的工程,所以主函數是_tmain。

// 鏈表.cpp : 定義控制台應用程序的入口點。
//

#include "stdafx.h"


typedef struct Node {
int data;
struct Node *next;

} LinkList;


//鏈表組合的函數 輸入:兩個有序無頭結點鏈表 輸出:將鏈表組合成一個無頭結點有序鏈表
LinkList * combie(LinkList *l1, LinkList * l2) {

LinkList * p=NULL;

if (l1==NULL && l2==NULL)
{
p = NULL;
}
if (l1==NULL&&l2!=NULL)
{
p = (LinkList *)malloc(sizeof(LinkList));
p->data = l2->data;
p->next = combie(NULL, l2->next);

}

if (l2 == NULL&&l1 != NULL)
{
p = (LinkList *)malloc(sizeof(LinkList));
p->data = l1->data;
p->next = combie(l1->next,NULL);

}
if (l1!=NULL && l2!=NULL)
{
p = (LinkList *)malloc(sizeof(LinkList));

p->data = l1->data <= l2->data ? l1->data : l2->data;
p->next = combie(l1->data <= l2->data ? l1->next : l1, l1->data <= l2->data ? l2 : l2->next);

}
return p;
}

//根據數組創建無頭結點的鏈表
LinkList * create(int a[], int n) {
LinkList *h = NULL, *p, *pre = NULL;
for (int i = 0; i < n; i++)
{
p=(LinkList *)malloc(sizeof(LinkList));
p->data = a[i];
if (pre) pre->next = p;
pre = p;
if (i == 0) h = p;
if (i == n - 1) p->next = NULL;

}
return h;


}


//打印輸出無頭結點的鏈表
void display(LinkList *list) {
LinkList *p = list;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;

}

int _tmain(int argc, _TCHAR* argv[])
{
int a []= { 1, 2, 10, 80,500 };
LinkList *l1 = create(a,5);
display(l1);
int b[] = { 0,4, 5, 100, 177,250 };
LinkList *l2 = create(b, 6);
display(l2);
LinkList * p = combie(l1, l2);
display(p);
system("pause");
return 0;
}

stdafx.h 的內容挺簡單的

// stdafx.h : 標准系統包含文件的包含文件,
// 或是經常使用但不常更改的
// 特定於項目的包含文件
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

// TODO: 在此處引用程序需要的其他頭文件
#include <iostream>
#include <cstdlib>
using namespace std;

Copyright © Linux教程網 All Rights Reserved