單鏈表的創建/打印/求長/兩兩反轉/排序
阿新 • • 發佈:2019-03-09
sin int 鏈表的創建 reat () 創建 getchar() space urn
#include <string> #include <iostream> using namespace std; struct Node{ int val; Node *next; }; Node *creat(){ int x =0 ; Node *head,*p; head = new Node; //關鍵 給head分配空間 p=head; while(cin>>x){ Node *s = new Node; s->val = x; p->next = s; p=s; if (getchar() == ‘\n‘) break; //關鍵 不然while(cin>>n)需要ctrl+z才能結束 } head = head->next; p->next = NULL; return head; } int length(Node *head){ if(head==NULL) return 0; int count=0; Node *p; p=head; while(p!=NULL){ p=p->next; count++; } // while(head!=NULL){ // head=head->next; // count++; // } // cout<<count<<endl; return count; } void print(Node * head){ Node *p ; p=head; while(p!=NULL){ cout<<p->val<<" "; p= p->next; } cout<<endl; } Node *reverse(Node *head){ Node *ans = new Node; ans->next = head; Node *cur = ans; while(cur->next!=NULL && cur->next->next!=NULL){ Node* node1 = cur->next; Node* node2 = node1->next; Node* rear = node2->next; cur->next = node2; node2->next = node1; node1->next = rear; //這一步改變了head->next,跳過了第二個 cur = node1; } return ans->next; } Node *sort(Node *head){ Node *p = head; int nums = length(head); int tmp; for(int i=0;i<nums-1;i++){ p = head; for(int j=0;j<nums-i-1;j++){ if(p->val > p->next ->val){ tmp = p->val; p->val = p->next ->val; p->next ->val = tmp; } p = p->next; } } return head; } int main() { Node * head; head = creat(); Node *s = sort(head); print(s); Node * rev = reverse(head); print(rev); }
單鏈表的創建/打印/求長/兩兩反轉/排序