#include <cstdio>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
int tot = 0;
Node *Node_Creat()
{
Node *head;
head = (Node *)malloc(sizeof(Node));
if(head == NULL)
{
printf("Overflow\n");
exit(1);
}
head = NULL;
Node *p1,*p2;
p1 = p2 = (Node *)malloc(sizeof(Node));
if(p1 == NULL || p2 == NULL)
{
printf("Overflow\n");
exit(1);
}
scanf("%d",&p1 -> data);
while(p1 -> data >= 0)
{
tot++;
if(head == NULL)
{
head = p1;
}
else
{
p2 -> next = p1;
}
p2 = p1;
p1 = (Node *)malloc(sizeof(Node));
if(p1 == NULL)
{
printf("Overflow\n");
exit(1);
}
scanf("%d",&p1 -> data);
}
p2 -> next = NULL;
return head;
}
void Node_Print(Node *head)
{
Node *p;
p = head;
if(p == NULL)
{
printf("EMPTY\n");
return ;
}
while(p != NULL)
{
printf("%d ",p -> data);
p = p -> next;
}
printf("\n");
}
Node *Reverse_Node(Node *head)
{
Node *pPrv = NULL;
Node *pNext = NULL;
Node *pNow = head;
Node *ReverseNode = NULL;
while(pNow != NULL)
{
pNext = pNow -> next;
if(pNext == NULL)
{
ReverseNode = pNow;
}
pNow -> next = pPrv;
pPrv = pNow;
pNow = pNext;
}
return ReverseNode;
}
Node * ReversePart_Node(Node *head,int start,int end)
{
Node *pPrv = NULL;
Node *pNow = head;
Node *pNext = NULL;
Node *BeforeStart = NULL; //开始的结点前的结点
Node *StartNode = NULL; //开始的时候的结点
int i,j;
//for循环指向需要反转的位置
for(i = 1; i <= start; i++)
{
if(i == start)
{
BeforeStart = pPrv;
StartNode = pNow;
}
pPrv = pNow;
pNow = pNow -> next;
pNext = pNow -> next;
}
for(i = 1; i <= end - start; i++)
{
pNext = pNow -> next; //保存下一个
pNow -> next = pPrv; //改变指向
pPrv = pNow; //移动 pPrv和 pNow
pNow = pNext;
}
//反转部分 未反转前的第一个结点 反转之后变成该反转部分的最后一个结点
StartNode -> next = pNow; //连接
if(BeforeStart == NULL) //从head开始反转
{
head = pPrv; //pNow 反转过后是 该反转部分的第一个结点
}
else
{
BeforeStart -> next = pPrv; //连接反转部分前面的结点 和 该反转部分
}
return head;
}
int main()
{
Node *head;
head = Node_Creat();
Node_Print(head);
head = Reverse_Node(head);
Node_Print(head);
int start,end;
scanf("%d%d",&start,&end);
head = ReversePart_Node(head,start,end);
Node_Print(head);
return 0;
}
链表反转部分结点功能的实现
最新推荐文章于 2024-11-17 22:56:44 发布