1 #include <iostream>
2
3 using namespace std; 4 5 struct Node 6 { 7 public: 8 int data; 9 Node *next; 10 Node(){}; 11 Node(int i) 12 { 13 data = i; 14 next = NULL; 15 } 16 }; 17 class List 18 { 19 public: 20 Node *head; 21 Node *curr; 22 List() 23 { 24 head = NULL; 25 curr = NULL; 26 } 27 void insert_from_tail(Node *tmp) 28 { 29 if(head == NULL) 30 { 31 head = new Node(); 32 head->next = tmp; 33 curr = tmp; 34 } 35 else 36 { 37 curr->next = tmp; 38 curr = tmp; 39 } 40 } 41 int length()const 42 { 43 int count = 0; 44 Node *tmp = head->next; 45 while(tmp != NULL) 46 { 47 tmp = tmp->next; 48 count++; 49 } 50 return count; 51 } 52 }; 53 //完成两个节点的值的交换 54 void Swap(Node *t1,Node *t2) 55 { 56 int tmp = t1->data; 57 t1->data = t2->data; 58 t2->data = tmp; 59 } 60 //冒泡排序 61 void bubble_sort(List &l) 62 { 63 int len = l.length(); 64 for(int i = len-1 ; i > 0 ; --i) 65 { 66 Node *tmp = l.head->next; 67 for(int j = 0 ; j < i ; ++j) 68 { 69 if(tmp->data > tmp->next->data) 70 { 71 Swap(tmp,tmp->next); 72 } 73 tmp = tmp->next; 74 } 75 } 76 } 77 //完成单链表的逆序并输出 78 void reverse_print(List &l) 79 { 80 if(l.head == NULL || l.head->next == NULL)//链表是空 81 { 82 return ; 83 } 84 Node *p1 = l.head->next; 85 Node *p2 = l.head->next->next; 86 p1->next = NULL;//这里一定要让p1->next = NULL,因为逆序后p1实际上是链表的最后一个节点 87 while(p2 != NULL) 88 { 89 Node *tmp = p2->next; 90 p2->next = p1; 91 p1 = p2; 92 p2 = tmp; 93 } 94 l.head->next = p1;//注意这里第一个节点是p1,而不是p2 95 Node *p = l.head->next; 96 while(p != NULL) 97 { 98 cout<<p->data<<" "; 99 p = p->next; 100 } 101 cout<<endl; 102 } 103 //合并两个单链表
关于链表的代码
最新推荐文章于 2022-12-04 14:10:30 发布