标签:int 插入 cto struct 创建 span 单链表 代码 main
代码鲁棒性较差,之后补充注释以及减少BUG增加可读性。
#include <iostream> #include <vector> #include <cstring> #include <malloc.h> using namespace std ; typedef struct Node{ int data ; struct Node *next ; }node , *Lnode ; int Linklist_length( node *head ){ node *p = (node*)malloc(sizeof(node)) ; int len = 0 ; while ( p ){ p = p->next ; len ++ ; } return len ; } Lnode Link_reverse_head( node *head ){ node *p = head->next ; head->next = NULL ; node *q ; while ( p ){ q = p ; p = p->next ; q->next = head->next ; head->next = q ; } return head ; } Lnode Linklist_insert( int pos , int num , node *head ){ node *index = head ; for ( int i = 0 ; i < pos ; i ++ ){ index = index->next ; } node *p = (node*)malloc(sizeof(node)) ; p->data = num ; p->next = index->next ; index->next = p ; return head ; } Lnode Linklist_delete( int pos , node *head ){ node *index = head ; for ( int i = 1 ; i < pos ; i ++ ){ index = index->next ; } node *p = index->next ; index->next = p->next ; p->next = NULL ; free( p ) ; return head ; } Lnode Creat_from_head( int count ){ node *head = (node*)malloc(sizeof(node)) ; head->next = NULL ; int num ; while ( count -- && cin >> num ){ node *p = (node*)malloc(sizeof(node)) ; p->data = num ; p->next = head->next ; head->next = p ; } return head ; } Lnode Creat_from_last( int count ){ node *head = (node*)malloc(sizeof(node)) ; head->next = NULL ; int num ; node *index = head ; while ( count -- && cin >> num ){ node *p = (node*)malloc(sizeof(node)) ; p->data = num ; index->next = p ; index = p ; } index->next = NULL ; return head ; } void output( node *head ){ node *p = head->next ; while ( p ){ cout << p->data << " " ; p = p->next ; } cout << endl ; return ; } int main(){ int num ; cin >> num ; node *index_creat = Creat_from_last( num ) ; output( index_creat ) ; int pos , number ; cin >> pos >> number ; node *index_insert = Linklist_insert( pos , number , index_creat ) ; output( index_insert ) ; cin >> pos ; node *index_delete = Linklist_delete( pos , index_creat ) ; output( index_delete ) ; // int len = Linklist_length( index_creat ) ; node *index_reverse = Link_reverse_head( index_creat ) ; output( index_reverse ) ; return 0 ; }
标签:int 插入 cto struct 创建 span 单链表 代码 main
原文地址:https://www.cnblogs.com/Cantredo/p/9688746.html