剛學了數據結構的單鏈表基本操作:創建,刪除,插入,反轉等,以下是詳細內容,其中很多關於數據結構的表述並不完整,只是簡單的基本演算法思想的表現。
由於沒經驗,代碼有點亂·····
如有不當或錯誤之處,歡迎指正,不勝感激!
- #include
- #include
- struct node
- {
- int data;
- struct node* next;
- }head;
- struct node *p,*q;
- void head_insert(int x)
- {
-
- p=(struct node*)malloc(sizeof(struct node));
- if(p==NULL)
- {
- printf("內存申請失敗,退出");
- exit(0);
- }
- p->data=x;
- p->next=head.next;
- head.next=p;
- }
- void tail_insert(int x)
- {
-
- p=(struct node*)malloc(sizeof(struct node));
- if(p==NULL)
- {
- printf("內存申請失敗,退出");
- exit(0);
- }
- p->data=x;
- p->next=NULL;
- q->next=p;
- q=p;
- }
- void node_length()
- {
- int length=0;
- p=head.next;
- if(p==NULL) printf("The length of node is 0.\n");
- else
- {
- do
- {
- length++;
- p=p->next;
- } while(p);
- printf("The length of node is %d.\n",length);
- }
- }
- void print_node()
- {
- printf("輸出此時鏈表:\n");
- p=head.next;
- if(p==NULL) {printf("NULL\n");return;}
- else
- {
- while(p)
- {
- printf("%d ",p->data);
- p=p->next;
- }
- printf("\n");
- }
-
- }
- void clear_node()
- {
- p=head.next;
- head.next=NULL;
- while(p)
- {
- q=p;
- p=p->next;
- free(q);
- }
- }
- void new_insert(int i,int a)
- {
- q=(struct node*)malloc(sizeof(struct node));
- q->data=a;
- p=head.next;
- if(i<0) printf("Position Error.\n");
- else
- {
- while(p&&--i) p=p->next;
- if(i) printf("Position Error.\n");
- else
- {
- q->next=p->next;
- p->next=q;
- }
- }
- }
- void delete_node(int i)
- {
- p=&head;
- while(p->next&&--i)
- p=p->next;
- if(i) printf("Position Error.\n");
- else
- {
- q=p->next;
- p->next=q->next;
- free(q);
- }
- }
- void invert_order()
- {
- node *This,*prev;
- p=head.next;
- This=NULL;
- while(p)
- {
- prev=This;
- This=p;
- p=p->next;
- This->next=prev;
-
- }
- head.next=This;
- }
- int main()
- {
- int number,i,a;
- head.next=NULL;
- q=&head;
- printf("輸入整型數據:\n");
- while(scanf("%d",&number)!=EOF)
- {
- head_insert(number);
-
-
- }
- invert_order();
- node_length();
- print_node();
- printf("在第i個位置后插入a,請輸入i和a:\n");
- scanf("%d%d",&i,&a);
- new_insert(i,a);
- print_node();
- printf("輸入要刪除的第i個結點:\n");
- scanf("%d",&i);
- delete_node(i);
- print_node();
- clear_node();
- return 0;
- }
附:在Windows下,輸入數據完畢后先按Enter鍵,再按Ctrl+Z鍵,最後按Enter鍵即可結束輸入;在Linux下,輸入完畢后按Ctrl+D鍵可結束輸入。