核心思想:借助两个指针
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>
#include <stdlib.h>//单链表结构体定义
typedef int ElemType;
typedef struct Node
{ElemType data;struct Node* next;
}LNode, *LinkList;//尾插法建立带头结点的单链表
void CreLinkListTail(LNode* L, int n)
{LNode* s, * r;ElemType x;int i;r = L;//r指针的初始化,首先指向链表Lprintf("带头结点尾插法--输入结点:\n");for (i = 0; i < n; i++){scanf("%d", &x);s = (LNode*)malloc(sizeof(LNode));s->next = NULL;s->data = x;//尾插r->next = s;//r的下一个结点是sr = s;//r指向s}r->next = NULL;
}//原地反转
void localReverse(LNode* L)
{if (L == NULL || L->next == NULL){return;}//借助两个指针来原地逆置链表LNode* beg = L->next;LNode* end = L->next->next;while (end != NULL){beg->next = end->next;end->next = L->next;L->next = end;end = beg->next;//end指针重新指向beg指针后一个结点}
}//输出链表信息
void OutPut(LNode* L)
{LNode* p;p = L;while (p != NULL){printf("%d ", p->data);p = p->next;}printf("\n");
}int main()
{int n;//n个结点printf("请在键盘中输入链表有几个结点:\n");scanf("%d", &n);//输入n个结点LNode* L = (LNode*)malloc(sizeof(LNode));//空链表的创建L->next = NULL;//指针域为空CreLinkListTail(L, n);//尾插法建立单链表printf("尾插法--输出建立后的单链表:\n");OutPut(L->next);//输出建立后的单链表localReverse(L);printf("逆置后的单链表:\n");OutPut(L->next);return 0;
}