问题描述:给个单链表,将它原地逆序(不借助其他空间)
程序:
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef struct node{
int data;
struct node *next;
}LinkList,*LList;
void f(LList head)
{
LList pre, p,nex;
pre = head->next;
p = pre->next;
pre->next = NULL;
while(p != NULL)
{
nex = p->next;
head->next = p;
p->next = pre;
pre = head->next;
p = nex;
}
}
int main()
{
int N;
LList head = new LinkList;
head->data = 1<<30;
head->next = NULL;
LList q = head;
cin>>N;
if(N == 0)
{
cout<<"链表为空"<<endl;
return 0;
}
while(N)
{
LList p = new LinkList;
cin>>p->data;
p->next = NULL;
q->next = p;
q = q->next;
N--;
}
f(head);
while(head->next != NULL)
{
cout<<head->next->data<<" ";
head = head->next;
}
cout<<endl;
system("pause");
return 0;
}