C++题目 求解答

〈1〉自己写一个strcmp函数,实现两个字符串的比较。两个字符串s1,s2由main函数输入,strcmp函数的返回值也在main函数中输出。〈2〉 动态链表的每个结点包括一个整数和一个后继指针。分别编写过程完成如下操作: (1) 从键盘输入数据建立链表,并按数据的输入顺序建立链表。 (2) 依次打印其中各结点的数据。

#include <iostream>
using namespace std;

int strcmp(char *s1, char *s2){
while(*s1 && *s2 && *s1 == *s2){
++s1;
++s2;
}
return *s1 - *s2;
}

int main(){
char s1[500] = {'\0'};
char s2[500] = {'\0'};
cout<<"s1:";cin>>s1;
cout<<"s2:";cin>>s2;
if(strcmp(s1, s2) == 0)
cout<<"s1等于s2"<<endl;
else if(strcmp(s1, s2) > 0)
cout<<"s1大于s2"<<endl;
else
cout<<"s1小于s2"<<endl;

return 0;
}

执行结果:

#include <iostream>
using namespace std;

class Node{
public:
int value;
Node *next;
Node(int value, Node *next){
this->value  = value;
this->next = next;
}
};

class LinkedList{
private:
Node *head;
public:
LinkedList(){
head = NULL;
}
void addNode(int val){
if(head == NULL)
head = new Node(val, NULL);
else{
Node *p = head;
//令p指针指向最后一个节点
while(p->next){
p = p->next;
}
p->next = new Node(val, NULL);
}
}
//显示元素
void mydisplay(){
Node *p = head;
for(;p != NULL;p=p->next)
cout<<p->value<<" ";
cout<<endl;
}
//析构函数
~LinkedList(){
Node *p = head;
Node *temp = NULL;
for(;p != NULL;){
temp = p->next;
delete p;
p = temp;
}

}
};

int main(){
LinkedList ll;
cout<<"输入链表数据以-1结束:"<<endl;
int val = 0;
while(true){
cin>>val;
if(val == -1)
break;
else
ll.addNode(val);
}
//打印元素
cout<<"打印元素"<<endl;
ll.mydisplay();
return 0;
}

执行结果:

追问

剩下两题呢

追答

另2题,已补充

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答