#include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef struct link { int num; struct link *next; }IA; IA *Create(); IA *Insert (IA *head, IA *p); void Print(IA *head); int main() { IA * head = NULL; int num; head = Create(); scanf("%d",num); Delete(head, num); return 0; } IA *Create() { IA *head = NULL, *p; int num; while(~scanf("%d",&num)&&num >= 0){ p = (IA*)malloc(sizeof(IA)); p -> num = num; head = Insert(head,p); } Print(head); return head; } IA *Insert(IA *head,IA *p) { IA *ptr, *ptr1, *ptr2; ptr = p; ptr1 = head;//ptr表示插入的,ptr1表示头文件,ptr2过渡 if(head == NULL){ head = p; p -> next = NULL; }//第一个数直接放入 else { while( ptr-> num > ptr1 -> num && ptr1 -> next!=NULL) { ptr2 = ptr1;//ptr2保存头指针 ptr1 = ptr1 -> next;//如果p的大小大于头指针那么头指针一直下去 } if(ptr -> num <= ptr1 -> num){ if(ptr1 == head) //头指针没移动,说明插在左边 head = ptr; //头指针就是p else ptr2 ->next = ptr;//如果头指针移动了那么头指针的下一个就是p ptr -> next = ptr1;//结束后p的下一个就是原来头指针 } else {//最后一个数 ptr1 ->next = ptr; ptr -> next = NULL; } } return head; } void Print(IA *head) { IA *p; if( head == NULL) return ; for( p = head; p != NULL; p = p -> next) printf("%d ",p -> num); printf("\n\n"); } VOID *Delete(IA *head, int num) { IA *ptr1, *ptr2; if(head == NULL) return ; while(head -> num == num){ //如果最小的数就是num那么第一个开始就替换 ptr1 = head; head = head -> next; free(ptr1); } ptr1 = head;//ptr1记录当前指针,ptr2记录下一个指针 ptr2 = head -> next; while(ptr2 != NULL){ //一直执行到最后 if(ptr2 -> num == num){//如果下一个指针的值就是num那么ptr1的下一个就是ptr2的下一,把ptr2覆盖了 ptr1 -> next = ptr2 -> next; free(ptr2); } else ptr1 = ptr2 -> next;//否则的话接下去遍历 ptr2 = ptr1 -> next; } Print(head); }
虽然注释了但还是写不出来,得慢慢磨orz
时间: 2024-10-10 05:12:15