//使用了三个指针,每次修改pnext指向pcurrent,然后移动三个指针
#include<iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
int a[5]={1,2,3,4,5};
int main(){
Node *head;
head=(Node *)malloc(sizeof(Node));
head->next=NULL;
for(int i=0;i<5;i++){
Node *tmp=(Node *)malloc(sizeof(Node));
tmp->data=a[i];
tmp->next=head->next;
head->next=tmp;
}
for(Node *tmp=head->next;tmp;tmp=tmp->next)
cout<<tmp->data<<" ";
cout<<endl;
Node* pcurrent,*pnext,*pnnext;
pcurrent=(Node *)malloc(sizeof(Node));
pnext=(Node *)malloc(sizeof(Node));
pnnext=(Node *)malloc(sizeof(Node));
pcurrent=head->next;
pnext=pcurrent->next;
pnnext=pnext->next;
int n=0;
while(pnnext!=NULL){
n++;
if(n==1)
pcurrent->next=NULL;
pnext->next=pcurrent;
pcurrent=pnext;
pnext=pnnext;
pnnext=pnnext->next;
}
if(pnext->next!=NULL)
pnext->next=pcurrent;
head->next=pnext;
for(Node *tmp=head->next;tmp;tmp=tmp->next)
cout<<tmp->data<<" ";
return 0;
}
给定一个链表的头指针,要求只遍历一次,将单链表中的元素顺序反转过来
最新推荐文章于 2022-03-05 22:41:59 发布