单链表创建,合并,剑指offer刷题
// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
struct Node{
int val;
struct Node* next;
};
Node* create(vector<int> v){
Node* head=NULL;
Node* tail = NULL;
head = (Node*)malloc(sizeof(Node));
head->val = v[0];
head->next = NULL;
tail = head;
for (int i = 1; i <(int)v.size(); i++){
Node* temp = (Node*)malloc(sizeof(Node));
temp->val = v[i];
temp->next = NULL;
tail->next = temp;
tail = tail->next;
}
return head;
}
Node* merge(Node* &l, Node* &r){
if (l == NULL) return r;
if (r == NULL) return l;
Node *pre1, *next2, *next1,*temp;
pre1 = l, next2 = r,next1=r;
for (pre1 = l; pre1 != NULL;){
temp = pre1;
pre1 = pre1->next;
for (next2 = r; next2 != NULL; next2 = next2->next){
if (next2->val>temp->val) break;
next1 = next2;
}
if (next2 == NULL){
next1->next = temp;
return r;
}
if (next1 == next2){
temp->next = next2;
next1 = temp;
r = temp;
continue;
}
temp->next = next2;
next1->next = temp;
}
return r;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> v1 = { 1, 3, 5, 7 ,9};
vector<int> v2 = { 2, 4, 6, 8 };
Node* l = create(v1);
Node* r = create(v2);
Node* result = merge(l, r);
cout << "hello World!";
return 0;
}