大致步骤:
一:创建一个新链表,遍历原链表的同时,将原链表的值复制给新链表
二:将新链表插入到原链表中(大致如下)
注:
1.头结点是不存有数据的
2.记得malloc后要free
3.*&是c++的写法,等同于c中的*
答案:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define SIZE 100
typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode* next;
} LinkNode;
void CreateListR(LinkNode*& L, ElemType a[], int n) {
LinkNode* s, * r;
L = (LinkNode*)malloc(sizeof(LinkNode));
L->next = NULL;
r = L;
for (int i = 0; i < n; i++) {
s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = a[i];
r->next = s;
r = s;
}
r->next = NULL;
}
void DispList(LinkNode* L) {
LinkNode* p = L->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void listExpansion(LinkNode*& L)
{
assert(L!=NULL); //避免传进空指针
LinkNode* l = L;
LinkNode* p= (LinkNode*)malloc(sizeof(LinkNode)); //建立一个新链表
p->next = NULL;
LinkNode* p1 = p; //复制新链表的头结点
while (l != NULL) //将原链表的值复制给新链表
{
LinkNode*s= (LinkNode*)malloc(sizeof(LinkNode));
s->data = l->next->data;
p1->next = s;
l = l->next;
p1 = p1->next;
if (l->next == NULL) //如果复制到最后一个结点就break
{
break;
}
}
p1 = NULL; //末尾接上NULL
l = L->next; //复制旧链表的头结点
p1 = p->next; //复制新链表的头结点
while (l!=NULL) //将新链表插入到原链表
{
LinkNode* l1 = l->next;
LinkNode* p2 = p1->next;
l->next = p1;
p1->next = l1;
p1 = p2;
l = l1;
}
}
int main() {
int a[SIZE];
int n, i;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
LinkNode* p;
CreateListR(p, a, n);
listExpansion(p);
// 释放链表内存
DispList(p);
LinkNode* temp;
while (p != NULL) { //归还申请空间
temp = p;
p = p->next;
free(temp);
}
return 0;
}