1.对顶一个链表,翻转该链表从m到n的位置。要求直接翻转而非申请新空间。
2.代码:
# include <iostream>
using namespace std;
//定义节点结构
typedef struct snode
{
int data;
snode *pnext;
snode(int value)
:data(value),pnext(NULL)
{}
}Node;
//声明函数
void Reveral(Node *Head, int star, int end);
void OutLink(Node *Head);
//反转函数
void Reveral(Node *Head, int star, int end)
{
Node *Now = Head->pnext;
for (int i = 0; i < star-1; i++)
{
Head = Now;
Now = Head->pnext;
}
Node *Pre = Now;
Now = Now->pnext;
Node *Next;
for (int i = 0; i < (end - star); i++)
{
Next = Now->pnext;
Now->pnext = Head->pnext;
Head->pnext = Now;
Pre->pnext = Next;
Now = Next;
}
}
//输出链表
void OutLink(Node *Head)
{
if (Head == NULL)
{
cout << "链表为空"<<endl;
}
else
{
Node *p = Head->pnext;
while (p)
{
cout << "->" << p->data;
p = p->pnext;
}
cout << endl;
}
}
//删除链表
void Destroy(Node *Head)
{
Node *next;
while (Head)
{
next = Head->pnext;
delete Head;
Head = next;
}
}
//主函数
int main()
{
int len = 10;
int start = 3;
int end = 7;
Node *Head = new Node(0);
for (int i = 0; i < len; i++)
{
Node *Now = new Node(rand() % 10);
Now->pnext = Head->pnext;
Head->pnext = Now;
}
cout << "反转前链表" << endl;
OutLink(Head);
Reveral(Head, start, end);
cout << "反转后链表" << endl;
OutLink(Head);
Destroy(Head);
return 0;
}
3.结果
反转前链表:
->4->2->8->8->4->9->0->4->7->1
反转后链表:
->4->2->0->9->4->8->8->4->7->1
请按任意键继续. . .