前言
单链表的定义
typedef struct LNode {
int data;
struct LNode *next;
}LNode, *LinkList;
注:以下均为带头结点的单链表
头插法建表
依次将每个数据结点插入在头结点之后,即链表元素的顺序与输入元素的顺序相反
代码如下:
bool List_HeadInsert(LinkList &L,int a[],int n) {
L = (LNode *) malloc(sizeof(LNode));
L->next = NULL;
LNode *s;
for(int i=0;i<n;i++) {
s = (LNode *) malloc(sizeof(LNode));
s->data = a[i];
s->next = L->next;
L->next = s;
}
return true;
}
尾插法建表
依次将每个数据结点插入在单链表最后,即链表元素的顺序与输入元素的顺序相同
代码如下:
bool List_TailInsert(LinkList &L,int *a,int n) {
L = (LNode *) malloc(sizeof(LNode));
L->next = NULL;
LNode *s,*p;
p = L;
for(int i=0;i<n;i++) {
s = (LNode *) malloc(sizeof(LNode));
s->data = a[i];
p->next = s;
p = s;
}
p->next = NULL;
return true;
}
问题描述
给出一个不为空的单链表,在不创建新的单链表的基础上将链表逆置;
设计思想
用指针p指向链表的第一个元素结点,将原链表置空(L->next==NULL),用指针p遍历,把结点中的元素取出赋值给新建的结点,再用头插法将新建结点插入到原链表中
代码实现
- 创建链表
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
- 链表初始化
bool InitList(LinkList &L) {
L = (LNode *) malloc(sizeof(LNode));
L->next = NULL;
return true;
}
- 尾插法建表
bool List_TailInsert(LinkList &L) {
LNode *p,*s;
p = L;
for(int i=0; i<5; i++) {
s = (LNode *) malloc(sizeof(LNode));
s->data = i;
p->next = s;
p = s;
}
p->next = NULL;
//创建的单链表:0 1 2 3 4
return true;
}
- 链表逆置
bool List_Reverse(LinkList &L) {
LNode *s,*p;
//p指针指向第一个元素
p = L->next;
//L指针的头结点与后续结点断开
L->next = NULL;
//p指针作为原列表的头指针去遍历每一个元素
while(p!=NULL) {
//头插法插入元素
s = (LNode *) malloc(sizeof(LNode));
s->data = p->data;
s->next = L->next;
L->next = s;
p = p->next;
}
return true;
}
完整代码
#include<cstdio>
#include<cstdlib>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
bool InitList(LinkList &L) {
L = (LNode *) malloc(sizeof(LNode));
L->next = NULL;
return true;
}
bool List_TailInsert(LinkList &L) {
LNode *p,*s;
p = L;
for(int i=0; i<5; i++) {
s = (LNode *) malloc(sizeof(LNode));
s->data = i;
p->next = s;
p = s;
}
p->next = NULL;
return true;
}
void PrintList(LinkList &L) {
LNode *p;
p = L->next;
while(p!=NULL) {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
bool List_Reverse(LinkList &L) {
LNode *s,*p;
p = L->next;
L->next = NULL;
while(p!=NULL) {
s = (LNode *) malloc(sizeof(LNode));
s->data = p->data;
s->next = L->next;
L->next = s;
p = p->next;
}
return true;
}
int main() {
LinkList L;
InitList(L)
List_TailInsert(L);
List_Reverse(L);
PrintList(L);
system("pause");
return 0;
}