cin>>p->data;用c++怎么写
时间: 2023-08-07 10:58:54 浏览: 184
在C++中,如果你想使用输入流来读取数据并将其存储在指针变量 "p" 所指向的对象的 "data" 成员中,可以使用以下代码:
```cpp
cin >> p->data;
```
这假设 "p" 是一个指向某个对象的指针,该对象有一个名为 "data" 的成员变量。通过 "p->data",你可以访问并修改该成员变量的值。使用输入流对象 "cin",将用户输入的值读取到 "p->data" 中。请确保在使用该代码之前,已经为指针 "p" 分配了内存空间。
相关问题
题目:下面有结构node的定义,指针head中存放着node节点组成 的单链表的首节点地址,函数odd(head)获取head指向链表 中的序号(注意不是node结构的data字段,且序号从0开始编号) 为奇数的节点,并将这些节点按原有序组成新链表返回。 要求新链表中的节点采用动态内存分配的方式构建, 从而不破坏原链表。如:head指向的链表为:1->2->3->4->5->6, 则odd(head)得到的链表为:2->4->6。请完成函数odd的编写 #include <iostream> #include <fstream> using namespace std; struct node { //链表节点定义 int data; node* next; }; node* odd(node* h) { /**********Program**********/ /********** End **********/ } int main() { int number; int temp; cin >> number; cin >> temp; node* head = NULL, * t, *tmp; head = new node; head->next = NULL; head->data = temp; t = head; for (int i = 1; i< number; i++) { cin >> temp; t->next = new node; t = t -> next; t->data = temp; t->next = NULL; } t = odd(head); tmp = t; cout << tmp->data; tmp = tmp->next; while (tmp) { cout << "->" << tmp->data; tmp = tmp->next; } cout << endl; return 0; }
以下是函数odd的实现代码:
```c++
#include <iostream>
using namespace std;
struct node { //链表节点定义
int data;
node* next;
};
node* odd(node* h) {
node* newHead = NULL; // 新链表的头指针
node* newTail = NULL; // 新链表的尾指针
node* current = h;
int index = 0;
while (current != NULL) {
if (index % 2 != 0) { // 如果序号为奇数
// 创建新节点
node* newNode = new node;
newNode->data = current->data;
newNode->next = NULL;
if (newHead == NULL) { // 如果新链表为空
newHead = newNode;
newTail = newNode;
} else {
newTail->next = newNode;
newTail = newNode;
}
}
current = current->next;
index++;
}
return newHead;
}
int main() {
int number;
int temp;
cin >> number;
cin >> temp;
node* head = NULL, * t, *tmp;
head = new node;
head->next = NULL;
head->data = temp;
t = head;
for (int i = 1; i < number; i++) {
cin >> temp;
t->next = new node;
t = t->next;
t->data = temp;
t->next = NULL;
}
t = odd(head);
tmp = t;
cout << tmp->data;
tmp = tmp->next;
while (tmp) {
cout << "->" << tmp->data;
tmp = tmp->next;
}
cout << endl;
return 0;
}
```
输入示例:
```
6
1 2 3 4 5 6
```
输出示例:
```
2->4->6
```
LinkList p = new Node; cout << "\n\t\t\t请输入第" << i + 1 << "个学生的姓名;学号;数据结构成绩;java成绩;linux成绩:" << endl; cout << "\t\t\t"; cin >> p->data.name >> p->data.id >> p->data.g[0] >> p->data.g[1] >> p->data.g[2]; p->next = L->next; L->next = p; cout<<"\n\t\t\t添加成功!";
这段代码是在使用C++语言实现链表的插入操作,具体来说:
- 首先,定义了一个指向Node类型的指针p,并使用new关键字为其分配内存空间,即创建了一个新的节点。
- 然后,使用cin语句从控制台输入该节点的数据,包括姓名、学号、数据结构成绩、Java成绩和Linux成绩。
- 接着,将该节点插入到链表L的头部,即将该节点的next指针指向L的第一个节点,再将L的头指针指向该节点。
- 最后,输出添加成功的提示信息。
这段代码的作用是将新的节点插入到链表的头部,即实现了头插法。