面試題17 合併兩個排序的鍊錶

2021-06-25 14:36:28 字數 3075 閱讀 4361

題目描述:輸入兩個單調遞增的鍊錶,輸出兩個鍊錶合成後的鍊錶,當然我們需要合成後的鍊錶滿足單調不減規則。

(hint: 請務必使用鍊錶。)

輸入:輸入可能包含多個測試樣例,輸入以eof結束。

對於每個測試案例,輸入的第一行為兩個整數n和m(0<=n<=1000, 0<=m<=1000):n代表將要輸入的第乙個鍊錶的元素的個數,m代表將要輸入的第二個鍊錶的元素的個數。

下面一行包括n個數t(1<=t<=1000000):代表鍊錶一中的元素。接下來一行包含m個元素,s(1<=t<=1000000)。

輸出:對應每個測試案例,

若有結果,輸出相應的鍊錶。否則,輸出null。

樣例輸入:

5 2

1 3 5 7 9

2 40 0

樣例輸出:

1 2 3 4 5 7 9

null

[cpp]view plain

copy

/*********************************

*   日期:2013-11-23

*   題號: 題目1519:合併兩個排序的鍊錶

*   結果:ac

*   總結:

**********************************/

#include

#include 

#include 

#include 

using

namespace

std;  

typedef

struct

listnodelistnode;  

//列印鍊錶

void

output(listnode*head)  

else

else

p = p->next;  

}  }  

}  //建立鍊錶

listnode* createlist(listnode *head,int

n)  

return

head;  

}  listnode* merge(listnode*head1,listnode*head2)  

//只有第乙個字串,無需合併,直接輸出

else

if(head2->next == null)  

//只有第二個字串,無需合併,直接輸出

else

if(head1->next == null)  

//合併

else

else

p3 = p3->next;  

}  //head1沒有遍歷完

while

(p1 != null)  

//head2沒有遍歷完

while

(p2 != null)  

return

head;  

}  }  

intmain()   

if(m != 0)  

//合併排序

head1 = merge(head1,head2);  

//列印鍊錶

if(head1 == null)  

else

}//while

return

0;  

}  

【方法二】

【解析】

*   日期:2013-11-23

*   題號: 題目1519:合併兩個排序的鍊錶

*   結果:ac

*   總結:

**********************************/

#include

#include 

#include 

#include 

using

namespace

std;  

typedef

struct

listnodelistnode;  

//列印鍊錶

void

output(listnode*head)  

else

else

p = p->next;  

}  }  

}  //建立鍊錶

listnode* createlist(listnode *head,int

n)  

return

head;  

}  //遞迴

listnode* merge(listnode*head1,listnode*head2)  

else

if(head2 == null)  

else

if(head1 == null)  

//合併

listnode *head = null;  

if(head1->value value)  

else

return

head;  

}  int

main()   

if(m != 0)  

//合併排序

head1 = merge(head1->next,head2->next);  

//列印鍊錶

if(head1 == null)  

else

}//while

return

0;  

}  

面試題17 合併兩個排序的鍊錶

題目 輸入兩個遞增排序的鍊錶,合併這兩個鍊錶並使新鍊錶中的結點仍然是按照遞增排序的。非遞迴 第一種方法 非遞迴 struct listnode listnode mergetwolist listnode plistonehead,listnode plisttwohead 如果第二個鍊錶為空,則第...

面試題17 合併兩個排序的鍊錶

struct listnode 面試題17 合併兩個排序的鍊錶 include stdafx.h include list.h include include listnode merge listnode phead1,listnode phead2 else return pmergedhead...

面試題17 合併兩個排序的鍊錶

題目 輸入兩個遞增排序的鍊錶,合併這兩個鍊錶使新鍊錶仍然是遞增排序的。題目還算簡單,就是要考慮的特殊情況挺多的。如下 struct listnode class solution else current current next current next null listnode newhead...