使用c++中的单链表完成问题(1)从键盘输入10个整数,产生顺序表,并输入结点值
- 提问者网友:我一贱你就笑
- 2021-03-08 23:52
(2)从键3盘输入1个整数,在顺序表中查找该结点的位置,若找到,输出结点的位置,若找不到,则显示"找不到"
→用单链表实现←
- 五星知识达人网友:duile
- 2021-03-09 00:57
- 1楼网友:轮獄道
- 2021-03-09 01:10
//实现链表倒置,如链表存储的是1,2,3,倒置后为3,2,1 #include <iostream> using namespace std; //定义链表 typedef struct node { int data; node * next; }node; //创建链表 node* createlist(int &n) { node *tmp, *head = null, *tail = null; int num; cin>>num; head = new node; if(head == null) { cout<<"no memory available!"; return null; } head->data = num; head->next = null; tail = head; for(int i=0; i<n-1; i++) { cin>>num; tmp = new node; if(tmp == null) { cout<<"no memory available!"; return null; } tmp->data = num; tmp->next = null; tail->next = tmp; tail = tmp; } return head; } //链表倒置 node* inversionlist(node *head) { if(head == null || head->next == null) { return head; } node *connode = head->next; node *curnode = connode->next; head->next = null; while(curnode != null) { connode->next = head; head = connode; connode = curnode; curnode = curnode->next; } connode->next = head; head = connode; return head; }
//打印 void printlist(node *head) { node *curnode = head; while(curnode != null) { cout<<curnode->data<<"\t"; curnode = curnode->next; } } //删除链表,释放内存 void deleteallnode(node *head) { node *p = null; while(head != null) { p = head; head = head->next; delete p; p = null; } } void main() { int n; cout<<"please input the number of node:"; cin>>n; node *head = createlist(n); node *newhead = inversionlist(head); printlist(newhead); deleteallnode(newhead);
}