本文主要為大家分享一篇如何刪除字串中的子串的問題,具有很好的參考價值,希望對大家有所協助。一起跟隨小編過來看看吧。
話不多說,直接上代碼。
演算法思想: 找到要刪除的第i個結點,逐個刪除。
#include <stdio.h>#include <stdlib.h>typedef char datatype;typedef struct node{ datatype x; struct node *next;}seqlist;// 建立帶頭結點的單鏈表seqlist *creat(){ seqlist *p,*s,*head=NULL; datatype ch; head=(seqlist *)malloc(sizeof(seqlist)); p=head; head->next=NULL; while((ch=getchar())!='\n') { s=(seqlist *)malloc(sizeof(seqlist)); s->x=ch; p->next=s; p=s; } p->next=NULL; return head;}// 單鏈表的遍曆1seqlist * display1(seqlist *head){ seqlist *p; p=head->next; while(p) { printf("%c",p->x); p=p->next; } printf("\n"); return head;}// 單鏈表的遍曆2 建立這個是因為傳回值為null時用1會造成錯誤。seqlist * display2(seqlist *head){ seqlist *p; p=head; while(p) { printf("%c",p->x); p=p->next; } printf("\n"); return head;}// 字串子串的刪除seqlist * Del(seqlist * head,int i,int len){ seqlist *p,*q,*r; // p,q,r 分別為移動,替死符,記錄前一個位子。 int k=1; p=r=head; while(p && k<=i) { r=p; p=p->next; k++; } if(!p) { printf("Error1\t 位置超出範圍\n"); return (NULL); } else { k=1; while(p && k<=len) //這裡需要特別注意出口條件 { if(p==r) { p=p->next; q=p; p=q->next; r->next=q->next; k++; free(q); } else { q=p; p=q->next; r->next=q->next; k++; free(q); } } if(k<len) { printf("Error 2\t長度超出範圍\n"); return (NULL); } else return head; }}int main(){ int i,len; seqlist *head; head=creat(); display1(head); scanf("%d",&i); scanf("%d",&len); head=Del(head,i,len); display2(head); return 0;}
相關推薦:
刪除指定字串中的子串
在字串中刪除子串
刪除字串中的子串