链表逆转(头插法)
#include <bits/stdc++.h>
using namespace std;
struct listnode
{
int val; //当前结点的值
listnode *next; //指向下一个结点的指针
listnode(int x) : val(x), next(NULL) {} //初始化当前结点值为x,指针为空
};
char c;
int num;
void reversePrintListNode(listnode* head)
{
listnode *p,*q,*L=new listnode(0);
L->next=NULL;
p=head;
while(p)
{
q=new listnode(0);
q->val=p->val;
q->next=L->next;
L->next=q;
p=p->next;
}
L=L->next;
while(L)
{
cout<<L->val<<" ";
L=L->next;
}
}
void create_list()
{
listnode* a=new listnode(0); //创建新元素
listnode* b=a;//最后的结果b指向a,这样可以获取a所接收的全部元素
for(int i=1;i<=9;i++)
{
cin>>num;
listnode* newnode = new listnode(num);
a->next=newnode;
a=newnode;
}
// while ((c = getchar()) != '\n') //以空格区分各个结点的值
// {
// if (c != ' ')
// {
// ungetc(c, stdin); //把不是空格的字符丢回去
// cin >> num;
// listnode* newnode = new listnode(0);
// newnode->val = num;//创建新的结点存放键盘中读入的值
// newnode->next = NULL;
// a->next = newnode;//并将其赋值给temp2
// a = newnode; //此处也可以写成 temp2=temp2->next,使指针指向下一个,以待接收新元素
// }
// }
reversePrintListNode(b->next);
}
int main()
{
create_list();
return 0;
}