思路
旧链表头删,新链表头插。
代码
//将链表就地逆置
#include<stdio.h>
#include<malloc.h>
typedef struct node{
int data;
struct node* next;
}ElemSN;
ElemSN* creatLink(int a[],int n)
{
ElemSN* h = NULL;
ElemSN* p;
for(int i = n-1;i>-1;i--){
p = (ElemSN*)malloc(sizeof(ElemSN));
p->data=a[i];
p->next=h;
h=p;
}
return h;
}
void PrintLink(ElemSN* h)
{
for(;h;h=h->next){
printf("%d\n",h->data);
}
}
//旧链表头删,新链表头插
ElemSN* PreLink(ElemSN* h)
{
ElemSN* hn=NULL;
ElemSN* p;
while(h){
p=h;
h=h->next;
p->next=hn;
hn=p;
}
return hn;
}
int main(void)
{
int a[] = {3,2,5,8,4,7,6,9};
int n = sizeof(a)/sizeof(a[0]);
ElemSN* head_1 = creatLink(a,n);
ElemSN* head_2 = PreLink(head_1);
PrintLink(head_2);
return 0;
}