设计算法以比较链串S1和链串S2的大小,若S1<S2,返回-1;若S1=S2,返回0;否则返回1
时间: 2023-06-01 10:02:40 浏览: 46
1. 首先比较S1和S2的长度,若S1长度小于S2长度,则S1<S2;
2. 若S1和S2的长度相同,则从头到尾逐个比较S1和S2中对应的字符的ASCII码值,直到出现不同的字符或者比较完所有字符为止;
3. 若在比较过程中出现了不同的字符,则根据它们的ASCII码值大小关系来判断S1和S2的大小关系;
4. 若比较完所有字符都相同,则S1=S2;
5. 根据比较结果返回-1、0或1。
算法实现:
```
int compareString(char* S1, char* S2) {
int len1 = strlen(S1);
int len2 = strlen(S2);
int len = len1 < len2 ? len1 : len2;
for (int i = 0; i < len; i++) {
if (S1[i] < S2[i]) {
return -1;
} else if (S1[i] > S2[i]) {
return 1;
}
}
if (len1 < len2) {
return -1;
} else if (len1 > len2) {
return 1;
} else {
return 0;
}
}
```
注:链串可以转化为字符数组来比较大小。
相关问题
设计算法以比较链串S1和链串S2的大小,若S1<S2,返回-1;若S1=S2,返回0;否则返回1。
1. 比较链串长度,短的链串小于长的链串。
2. 从链串的头开始逐个比较节点的值,直到遇到不同的节点或其中一个链串结束。
3. 如果两个链串都结束了,说明它们相等,返回0;否则,结束位置在后面的链串大于结束位置在前面的链串,返回1;否则,返回-1。
算法实现如下:
```
int compareListString(ListNode* S1, ListNode* S2) {
int len1 = getListStringLength(S1);
int len2 = getListStringLength(S2);
if (len1 < len2) {
return -1;
} else if (len1 > len2) {
return 1;
} else {
while (S1 != nullptr && S2 != nullptr) {
if (S1->val < S2->val) {
return -1;
} else if (S1->val > S2->val) {
return 1;
} else {
S1 = S1->next;
S2 = S2->next;
}
}
if (S1 == nullptr && S2 == nullptr) {
return 0;
} else {
return (S1 == nullptr) ? -1 : 1;
}
}
}
```
其中,getListStringLength是获取链串长度的函数,实现如下:
```
int getListStringLength(ListNode* head) {
int len = 0;
while (head != nullptr) {
len++;
head = head->next;
}
return len;
}
```
设计算法以比较链串S1和链串S2的大小,若S1 < S2,返回-1;若S1 = S2,返回0;否则返回1。
1. 分别遍历S1和S2,比较每个字符的ASCII码值大小,若S1的字符小于S2的字符,则返回-1;若S1的字符大于S2的字符,则返回1;若遍历完S1和S2发现它们完全相同,则返回0。
2. 若S1和S2的长度不同,先比较它们的长度,长度较短的链串小于长度较长的链串。
代码示例:
```
int compare(String S1, String S2) {
int len1 = S1.length();
int len2 = S2.length();
int len = len1 < len2 ? len1 : len2; // 取较短的长度
for (int i = 0; i < len; i++) {
if (S1.charAt(i) < S2.charAt(i)) {
return -1;
} else if (S1.charAt(i) > S2.charAt(i)) {
return 1;
}
}
if (len1 < len2) {
return -1;
} else if (len1 > len2) {
return 1;
} else {
return 0;
}
}
```