標籤:including init cst rom ast ever include each 檔案
先上代碼,抽空再補充
reverse_list.cpp:
1 /* reverse singly linked list by adding each node after head from 2 * node 2 to node N; then add head after the last node. 3 */ 4 #include "init_list.h" 5 6 ListNode *reverseList(ListNode *head) { 7 ListNode *p = head->next, *q; 8 while(NULL != p->next) { 9 q = p->next;10 p->next = q->next;11 q->next = head->next;12 head->next = q;13 }14 p->next = head;15 head = p->next->next;16 p->next->next = NULL;17 return head;18 }19 20 ListNode *reverse2List(ListNode *head) {21 ListNode *p, *q, *r;22 if (NULL == head || NULL == head->next) {23 return head;24 }25 p = head;26 q = head->next;27 head->next = NULL;28 while (q) {29 r = q->next;30 q->next = p;31 p = q;32 q = r;33 }34 return p; /* head = p */35 }36 37 void reverse3List(ListNode *head) {38 if (NULL == head || NULL == head->next) {39 return head;40 }41 else {42 ListNode* newhead = reverse3List(head->next);43 head->next->next = head;44 head->next = NULL;45 return newhead;46 }47 }48 int main()49 {50 ListNode *head = createList();51 ListNode *newlist = reverse3List(head);52 cout << "reversed list is : " << endl;53 printList(newlist);54 return 0;55 }
標頭檔:init_list.h
#include <iostream>using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};ListNode *createList();void printList (ListNode *phead);ListNode *insertionSortList(ListNode *head);
初始設定檔案: init_list.cpp
1 /* 2 * init_list.cpp -- created to make some initiation of singly-linked list. 3 * including struct ListNode{} 4 * LN *createList(), void printList(*head),LN *insertionSortList(*head); 5 * author -- zhy 6 * date -- 2016-12-12 7 */ 8 9 #include <iostream>10 #include "cstdlib"11 using namespace std;12 13 /**14 * Definition for singly-linked list.15 */16 struct ListNode {17 int val;18 ListNode *next;19 ListNode(int x) : val(x), next(NULL) {}20 };21 22 23 ListNode *createList () {24 int i = 0, n;25 cout << "Please input the length N of your list: ";26 cin >> n;27 cout << "now input n values of your list: " << endl;28 ListNode *list = new ListNode(0);29 ListNode *head = list;30 for(; i < n; ++i)31 {32 head->next = new ListNode(0);33 head = head->next;34 cin >> head->val;35 }36 head = list->next;37 return head;38 }39 40 void printList (ListNode *phead) {41 while (NULL != phead){42 cout << phead->val << ‘ ‘;43 phead = phead->next;44 }45 cout << endl;46 }47 48 ListNode *insertionSortList(ListNode *head) {49 if (!head || !head->next)50 return head;51 ListNode *dummy = new ListNode(-1);52 ListNode *cur = head, *pre = dummy;53 while (NULL != cur) {54 pre = dummy;55 while (NULL != pre->next && pre->next->val < cur->val) {56 pre = pre->next; //find suitable position to insert57 }58 ListNode *temp = new ListNode(cur->val);59 temp->next = pre->next;60 pre->next = temp;61 62 cur = cur->next;63 //pre = dummy;64 }65 return dummy->next;66 }
鏈表反轉