微软笔试题
1 #include<iostream> 2 using namespace std; 3 4 /* 5 链表节点 6 */ 7 struct Node 8 { 9 int value; 10 Node* next; 11 }; 12 /* 13 创建一个长度为len的链表,并返回链表头结点 14 */ 15 Node* init(int len) 16 { 17 Node* head = new Node[len]; 18 if(head == NULL) 19 { 20 cout<<"new failed"<<endl; 21 return NULL; 22 } 23 Node* p = head; 24 for(int i = 1; i <= len ;p++, i++) 25 { 26 if( i < len ) 27 { 28 p->value = i; 29 p->next = p+1; 30 } 31 else 32 { 33 p->value = i; 34 p->next = NULL; 35 } 36 } 37 return head; 38 } 39 40 /* 41 接受一个链表头结点,并将链表逆置,返回链表头结点 42 */ 43 Node* reverse(Node* head) 44 { 45 if(head == NULL) 46 { 47 cout<<"链表为空"<<endl; 48 return NULL; 49 } 50 if(head->next == NULL) 51 return head; 52 Node* n_head = reverse(head->next); 53 head->next->next = head; 54 head->next = NULL; 55 return n_head; 56 } 57 58 /* 59 遍历一个链表 60 */ 61 void traverse(Node* head) 62 { 63 Node* ptr = head; 64 while( ptr != NULL ) 65 { 66 if(ptr->next != NULL) 67 cout<<ptr->value<<"->"; 68 else 69 cout<<ptr->value<<endl; 70 ptr = ptr->next; 71 } 72 } 73 /* 74 0->1->2->3->4 ===>> 0->4->1->3->2 75 0->1->2->3 ===>> 0->3->1->2 76 思路: 77 1、找到len/2+1的节点,生成两个链表a,b 78 2、将b链表逆置 79 3、将逆置后的b一个个插入a链表中 80 */ 81 void function(Node* head, int len) 82 { 83 if(head == NULL || len <= 0) 84 return; 85 int n_list_len = len/2 + 1; 86 Node* n_head = NULL; 87 Node* temp = head; 88 for(int i = 1; i < n_list_len; i++) 89 temp = temp->next; 90 n_head = temp->next; 91 temp->next = NULL; 92 Node* a = head; 93 Node* b = reverse(n_head); 94 while( b != NULL) 95 { 96 temp = b; 97 b = b->next; 98 temp->next = a->next; 99 a->next = temp; 100 a = temp->next; 101 } 102 } 103 104 int main() 105 { 106 Node* head; 107 int len = 0; 108 while(1) 109 { 110 cout<<"链表长度:"; 111 cin>>len; 112 if(len <= 0) 113 { 114 cout<<"链表长度不能小于等于0"<<endl; 115 continue; 116 } 117 head = init(len); 118 traverse(head); 119 function(head,len); 120 traverse(head); 121 head = reverse(head); 122 traverse(head); 123 } 124 return 0; 125 }