@【数据结构】(单链表元素变换)
设线性表A=(a1,a2,a3,…,an)以带头结点的单链表作为存储结构。编写一个函数,对A进行调整,使得当n为奇数时A=(a2,a4,…,an-1,a1,a3,…,an);当n为偶数时A=(a2,a4,…, an,a1,a3,…,an-1)
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
typedef struct list
{
int data;
struct list *next;
}*LIST, LNode;
void InitList(LIST *L) /* 初始化链表 */
{
*L = (LNode *)malloc(sizeof(LNode)); //带头结点的链表初始化
(*L)->next = NULL;
}
void OutputList(LIST L)
{
LNode *p;
p = L->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
}
//在带头结点的单链表的表尾插入元素,建立一个单链表,按*键结束
LIST CreateList(LIST L)
{
LNode *R;
int x;
R = L;
cout << "请输入线性表中的元素,输入-1结束:" << endl;
cin >> x;
while (x != -1)
{
R->next = (LNode *)malloc(sizeof(LNode));
R->next->data = x;
R = R->next;
cin >> x;
}
R->next = NULL;
return L;
}
void main()
{
int n;
cout << "请输入线性表中的元素个数n:";
cin >> n;
LIST L;
LNode *p,*q,*r;
InitList(&L);
CreateList(L);
cout << endl;
cout << "线性表A 为" << endl;
OutputList(L);
cout << endl;
p = L;
q = p->next;
while (q&&q->next)
{
r = q->next;
q->next = r->next; //删除偶数结点
r->next = p->next;
p->next = r;
p = p->next; q = q->next;
}
cout << "调整后线性表为:" << endl;
OutputList(L);
cout << endl;
system("pause");
}
单链表中元素个数与元素值由键盘输入。
测试示例: