2016.5.25——链表初始化及输出
链表初始化及输出
刷lleetcode题时不会写mian函数,于是把链表的几种输出总结一下。
1 #include "stdafx.h" 2 #include "iostream" 3 #include "vector" 4 #include "string" 5 using namespace std; 6 7 struct ListNode 8 { 9 char val; 10 ListNode *next; 11 ListNode(char x) : val(x), next(NULL){}; 12 }; 13 14 //单个节点值输入1 15 int _tmain(int argc, _TCHAR* argv[]) 16 { 17 ListNode *head1, *head2, *node1,*node2,*node3; 18 node1 = new ListNode(2); 19 node2 = new ListNode(5); 20 node3 = new ListNode(8); 21 22 //head1 = node1; 23 //node1->next = node2; 24 //node2->next = node3; 25 //node3 ->next = NULL; 26 head2 = node3; 27 node3->next = node2; 28 node2->next = node1; 29 node1->next = NULL; 30 while (head2 != NULL) 31 { 32 //cout << "aa" << endl; 33 cout << head2->val << " "; 34 head2 = head2->next; 35 } 36 cout << endl; 37 system("pause"); 38 return 0; 39 } 40 41 //单个节点值输入2 42 int main() 43 { 44 ListNode head(0), node1(1), node2(3),node3(3); 45 head.next = &node1; //head.next 46 node1.next = &node2; 47 node2.next = &node3; 48 node3.next = NULL; 49 while (head.next != NULL) 50 { 51 //cout << head.val << endl; 52 //if (head.next == NULL) 53 //{ 54 // cout << "aa" << endl; 55 // break; 56 //} 57 cout << head.val <<' '; 58 head = *(head.next); 59 } 60 cout << endl; 61 system("pause"); 62 return 0; 63 } 64 65 //固定数组输入 66 int main() 67 { 68 vector<int> nums = { 0, 1, 2, 3 }; 69 ListNode *head, *node; //指针时一定注意为NULL,会出错,防止为NULL,可用if语句,看是否进if语句 70 head = new ListNode(nums.at(0)); 71 for (size_t i = 1; i < nums.size(); i++) 72 { 73 node = new ListNode(nums.at(i)); 74 head->next = node; //这两句注意是谁 75 head = head->next; 76 cout << head->val << ' '; 77 } 78 cout << endl; 79 system("pause"); 80 return 0; 81 } 82 83 //动态输入 84 int main() 85 { 86 int nums[4] = {}; 87 for (int i = 0; i < 4; i++) 88 cin >> nums[i] ; 89 90 ListNode *head, *node; 91 head = new ListNode(nums[0]); 92 for (int j = 0; j < 4; j++) 93 { 94 node = new ListNode(nums[j]); 95 head->next = node; 96 head = head->next; 97 cout << head->val << " "; 98 } 99 cout << endl; 100 system("pause"); 101 return 0; 102 } 103 104 int main() 105 { 106 char nums[4] = {}; 107 for (int i = 0; i < 4; i++) 108 cin >> nums[i]; 109 110 ListNode *head, *node; 111 head = new ListNode(nums[0]); 112 for (int j = 0; j < 4; j++) 113 { 114 node = new ListNode(nums[j]); 115 head->next = node; 116 head = head->next; 117 cout << head->val << " "; //字符串型,不仅需要改main函数,还需要改struct中的类型 118 } 119 cout << endl; 120 system("pause"); 121 return 0; 122 }
posted on 2016-05-25 16:13 zhuzhu2016 阅读(186) 评论(0) 编辑 收藏 举报