您的位置:首页 > 理论基础 > 数据结构算法

数据结构_单链表的逆置

2015-09-15 20:05 543 查看
#include <iostream>

using namespace
std;

typedef struct s{
int data ;
struct
s *next;
}List ;

void TrailCreateList(List *L,int n)
//尾插法

{
List *r = L;
List *s;
for(int i =
0;i < n;++i)
{
s = (List *)malloc(sizeof(List));
int a;
cin >> a;
s -> data = a;
r -> next = s;
r = s;
}
r -> next =
NULL;
}

void HeadCreateList(List *L,int n)
//头插法

{
for(int i =
0;i < n;++i)
{
List *s = (List *)malloc(sizeof(List));
int a;
cin >> a;
s -> data = a;
s -> next = L ->
next;
L -> next = s;
}
}

void ListInsert(List *L,int i,int e)
//插入

{
List *r = L;
int j =
0;
while(r && j < i -
1)
{
r = r -> next;
j++;
}
List *s = (List *)malloc(sizeof(List));
s -> data = e;
s -> next = r ->
next;
r -> next = s;
}

void ListDisplay(List *L)
//输出
{
List *r = L ->
next;
while(r)
{
cout << r ->
data << " ";
r = r -> next;
}
cout <<
endl;
}

void ListDelete(List *L,int i,int &e)
//删除元素

{
List *r = L;
int j =
0;
while(r ->
next && j < i - 1)
{
r = r -> next;
++j;
}
List *q = r ->
next;
e = q -> data;
r -> next = q ->
next;
free(q);
}

void ListGet(List *L,int i,int &e)
//取元素
{
List *r = L ->
next;
int j =
1;
while(r && j < i)
{
r = r -> next;
++j;
}
e = r -> data;
}

void ListLocate(List *L,int e,int &i)
//寻找元素

{
List *r = L ->
next;
int j =
1;
while(r)
{
if(r ->
data == e)
{
i = j;
return ;
}
r = r -> next;
j++;
}
i = -1;
}

void nizhi(List *L,int n)
//逆置单链表

{
if(n ==
1)
return ;
else
if(n == 2)
{
List *r = L ->
next;
List *q = r ->
next;
L -> next = q;
q -> next = r;
r -> next =
NULL;
}
else
{
List *pre,*now,*last;
pre = L -> next;
now = pre -> next;
last = now -> next;
pre -> next =
NULL;
while(last)
{
now -> next = pre;
pre = last -> next;
pre = last;
last = last -> next;
List *t = pre;
pre = now;
now = t;
}
now -> next = pre;
L -> next = now;
}
}

void InverseList(List *L)

{
List *p = L ->
next;
List *q = p ->
next;
p -> next =
NULL;
p = q;
while(q !=
NULL)
{
q = q -> next;
p -> next = L ->
next;
L -> next = p;
p = q;
}
}

int main(){
List *L;
L = (List *)malloc(sizeof(List));
int n;
cout <<
"请输入一个n:";
cin >> n;
TrailCreateList(L,n);
//尾插法建立链表
/*//HeadCreateList(L,n); //
头插法建立链表
ListDisplay(L);
int willInsertI,willInsert; //插入元素
cin >> willInsertI >> willInsert;
ListInsert(L,willInsertI,willInsert);
ListDisplay(L);
int willDeleteI,willDelete; //删除元素
cin >> willDeleteI;
ListDelete(L,willDeleteI,willDelete);
ListDisplay(L);
cout << willDelete << endl;
int willGetI,willGet; //取元素
cin >> willGetI;
ListGet(L,willGetI,willGet);
cout << willGet << endl;
int willFindI = -1; //找元素
int willFind;
cin >> willFind;
ListLocate(L,willFind,willFindI);
if(willFindI != -1)
cout << willFindI << endl;
else
cout << "没有找到这个元素" << endl;
nizhi(L,n); // 逆置单链表
ListDisplay(L);*/
InverseList(L);
ListDisplay(L);
return
0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: