#include<bits/stdc++.h>
using namespace std;
/*
created by zhangwei
2018/4/24
*/
struct Node{
int d;
Node* nex;
};
Node *create()
{
struct Node *head = NULL,*q,*p;
int x;
while(scanf("%d",&x) == 1 && x!=-1){
Node *p = (struct Node*)malloc(sizeof(Node));
if(!head){
p->d = x;
head = q = p;
p->nex = NULL;
}
else{
p->d = x;
q->nex = p;
q = p;
}
q->nex = NULL;
}
return head;
}
void print(Node * head){
Node *p = head;
while(p){
printf("%d ",p->d);
p = p->nex;
}
printf("\n");
}
Node * reverse(Node *head){
Node *L = head;
Node *cur = head,*cur_nex = cur->nex,*front = head;
front->nex = NULL; //反转的第一个元素 的nex需要指向为NULL
while(cur_nex){
front = cur;
cur = cur_nex;
cur_nex = cur->nex;
cur->nex = front;
}
return head = cur;
}
int main()
{
Node *head = create();
printf("原链表: \n");
print(head);
head = reverse(head);
printf("反转后的链表:\n");
print(head);
return 0;
}
链表的创建与反转
最新推荐文章于 2025-04-20 16:49:26 发布