幾道筆試題的解法 一

2021-05-22 03:14:54 字數 2544 閱讀 9146

題目:

編寫乙個鍊錶合併程式。存在2個有序鍊錶list1,list2,要求合併為有序鍊錶list3。

分析: 本題主要考察鍊錶的建立和合併(有序的插入)

**如下:(宣告:部分**參考自網上)

#include "stdafx.h"

#include

using namespace std;

/* 單鏈表節點*/

struct node ;

/* 給單鏈表新增節點*/

void insertnode(node* head, int value)

while ( p->next != null )

node* tmp = new node;

tmp->value = value;

tmp->next = null;

p->next = tmp; }

/* 遍歷輸出鍊錶節點*/

void print(node* head)

cout << endl; }

/* 利用一般的方法進行合併,形成整體遞增有序*/

node* formalmerge(node* heada, node* headb)

if ( q == null )

while ( (p != null) && (q != null) )

else if ( p->value < q->value )

else if ( p->value > q->value )

} while ( p != null )

while ( q != null )

return head; }

/* 調整鍊錶的第乙個節點,使其變成遞增有序*/

void chg2sort(node* head, node* &p)

node* s = head;

while ( s->next != p ) //s指向p

的前乙個節點

//下面的一段找到第乙個大於

p節點值的節點

node* q = p;

node* r = q;

while ( q != null )

else

} //下面調整指標,其實可以統一寫出來,為了閱讀清晰把q為

null

和非null

分開寫出來

if ( q == null )

else if ( q != null )

//由於鍊錶進行了調換,當前鍊錶指標也需要改變

p = s->next; }

node* merge(node* head1, node* head2)

else if ( q == null )

//兩個都不為空

,先確定哪個鍊錶作為合併後的鍊錶

if ( (p != null) && (q != null) )

else

} node* p_prior; //

始終指向

p節點的前乙個節點

node* q_prior;

while ( (p != null) && (q != null) )

else if ( head == head2 )

} else if ( p->value == q->value )

else if ( p->value > q->value )

else if ( head == head2 )

} }

if ( p != null )

if ( q != null )

return head; }

int main() ;

node* heada = new node;

heada->next = null;

for (int i = 0; i < 5; ++i)

print(heada);

/* 建立有序鍊錶

b */

int b[3] = ;

node* headb = new node;

headb->next = null;

for (int i = 0; i < 3; ++i)

print(headb);

/* 利用簡單合併的方法合併成整體有序*/

node* head = formalmerge(heada, headb);

print(head);

int c[3] = ;

node* headc = new node;

headc->next = null;

for (int i = 0; i < 3; ++i)

print(headc);

//test chg2sort

chg2sort(headc, headc->next);

print(headc);

head = merge(heada, headb);

print(head);

return 0; }

幾道筆試題

出處 一 程式設計題 30分 現代的處理器提供了compare and swap原子操作 int compare and swap int pv,const int cv,const int nv 即比較 pv與cv,如果相等,則把 pv值替換為nv並返回 pv原值,否則返回 pv的值。請利用上述原...

幾道筆試題

1.在開啟的子視窗重新整理父視窗的 如何寫?window.opener.loaction.reload 2.寫出乙個ajax post請求伺服器資源並提公升返回資料的 片段,可以使用你熟悉的任何第三方js框架。ajax sucess function retval error function 3....

幾道C 筆試題

include using namespace std class a void fun virtual void print intm class b publica intmain 上例執行結果表明 1.建構函式中呼叫虛函式,無法實現多型。2.通過非虛函式呼叫虛函式,也可以實現多型。includ...