设单链表中存放着n个字符,每个节点保存一个字符。试编写算法,判断该字符串是否有中心对称关系。
作者:互联网
1 #include<iostream> 2 #include<cstring> 3 #include<cstdlib> 4 using namespace std; 5 struct node* create1(string); 6 struct node* create2(string); 7 struct node 8 { 9 char elem; 10 struct node* next; 11 }; 12 int main() 13 { 14 char str[40]; 15 cin >> str; 16 struct node* p1 = create1(str); 17 struct node* p2 = create2(str); 18 //while(strcmp(p1->elem,p2->elem)) 19 for (int i = 0; i < strlen(str); i++) 20 { 21 if (p1->elem == p2->elem) 22 { 23 p1 = p1->next; 24 p2 = p2->next; 25 } 26 else 27 { 28 cout << str << " is not symmetrical"; 29 break; 30 } 31 } 32 if (p1 == NULL && p2 == NULL) 33 cout << str << " is symmetrical"; 34 return 0; 35 } 36 struct node* create1(string s) 37 { 38 int n = s.length(); 39 struct node* head = NULL, * p1, * p2; 40 p2 = p1 = (struct node*)malloc(sizeof(struct node)); 41 for (int i = 0; i < n; i++) 42 { 43 if (head == NULL) 44 head=p1; 45 else 46 p2->next = p1; 47 p1->elem = s[i]; 48 p2 = p1; 49 //p1->elem = s[i]; 50 p1 = (struct node*)malloc(sizeof(struct node)); 51 } 52 p2->next = NULL; 53 free(p1); 54 return head; 55 56 } 57 struct node* create2(string s) 58 { 59 int n = s.length(); 60 struct node* head = NULL, * p1; 61 p1= (struct node*)malloc(sizeof(struct node)); 62 for (int i = 0; i < n; i++) 63 { 64 p1->elem = s[i]; 65 p1->next = head; 66 head = p1; 67 p1 = (struct node*)malloc(sizeof(struct node)); 68 } 69 free(p1); 70 return head; 71 }
标签:node,p2,单链,struct,中心对称,elem,next,p1,表中 来源: https://www.cnblogs.com/xu-chen-313/p/14598870.html