1. 问题描述:
有一个线性表,采用带有头结点的单链表L来进行存储,设计一个算法将其逆置,要求不能够建立新节点只能够通过表中已有的节点进行重新组合来完成
2. 思路分析:
① 我们知道链表建立的头插法中的元素顺序与原来的插入的顺序是相反的,所以我们可以将链表L中的元素作为逆转后L的元素来源,即将L->next设置为空,然后将头结点后的一串节点使用头插法逐个插入到L中,这样新的L中的顺序正好是逆序的,并且需要注意的是在使用尾插法的时候我们首先要保存链表需要插入节点的下一个节点,因为我们在插入节点的时候需要修改当前节点的next指针域,假如没有保存当前插入节点的下一个节点那么就会找不到下一个节点从而导致插入失败
② 在翻转链表之前我们可以使用提供的数组用头插法来创建出一个链表,然后再进行翻转
3. 下面是具体的代码:
#include<stdio.h>
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct node{
int data;
node *next;
}LNode;
LNode *L;
LNode* createList(LNode *L, int arr[], int n){
L = (LNode*)malloc(sizeof(LNode));
LNode *p = L;
for(int i = 0; i < n; ++i){
LNode *newNode = (LNode*)malloc(sizeof(LNode));
newNode->data = arr[i];
newNode->next = NULL;
p->next = newNode;
p = p->next;
}
return L;
}
LNode* reverse(LNode *L){
LNode *p = L->next;
LNode *q;
L->next = NULL;
while(p != NULL){
q = p->next;
p->next = L->next;
L->next = p;
p = q;
}
return L;
}
int main(void){
int arr[] = {100, 13, 34, 67, 23, 11, 89};
LNode *originlist = createList(L, arr, 7);
LNode *p = reverse(originlist);
while(p->next != NULL){
printf("%d ", p->next->data);
p = p->next;
}
}
#include<stdio.h>
#include<malloc.h>
typedef struct node{
int data;
node *next;
}LNode;
LNode *L;
LNode* createList(LNode *L, int arr[], int n){
L = (LNode*)malloc(sizeof(LNode));
LNode *p = L;
for(int i = 0; i < n; ++i){
LNode *newNode = (LNode*)malloc(sizeof(LNode));
newNode->data = arr[i];
//注意需要写上下面的将next指针域置为空的语句
newNode->next = NULL;
p->next = newNode;
p = p->next;
}
return L;
}
LNode* reverse(LNode *L){
LNode *p = L;
LNode *q = p->next;
p->next = NULL;
LNode *temp;
while(q != NULL){
temp = q->next;
q->next = p->next;
p->next = q;
q = temp;
}
return p;
}
int main(void){
//链表是存在头结点的
int arr[] = {100, 13, 34, 67, 23, 11, 89};
LNode *originlist = createList(L, arr, 7);
LNode *p = reverse(originlist);
while(p->next != NULL){
printf("%d ", p->next->data);
p = p->next;
}
}