链表逆序和是否有环



#include<iostream>
using namespace std;

struct Node
{
 int data;
 Node *next;

};
typedef struct Node Node;

Node *create()
{
 Node *head = NULL;//表头指针,一开始没有任何结点,所以为NULL
 Node *pEnd = head;//表为指针,一开始没有任何结点,所以指向表头
 Node *pS;//创建新结点时使用的指针
 for (int i = 0; i < 10;i++)
 {  pS = new Node;//创建新结点
   pS->data =i;
   pS->next = NULL;//新结点将成为表尾,所以next为NULL
   if (head == NULL)//如果链表还没有任何结点存在
   {
    head = pS;//则表头指针指向这个新结点
   }
   else
   {
    pEnd->next = pS;//把这个新结点连接在表尾
   }
   pEnd = pS;//这个新结点成为了新的表尾
   }

 return head;//返回表头指针
}
void showList(Node *head)
{
 Node *pRead = head;//访问指针一开始指向表头
 while (pRead != NULL)
 {
  cout << pRead->data;
  pRead = pRead->next;
 }
 cout << endl;
}

Node *reverse(Node *head)
{
 
 if (head == NULL || head->next == NULL)
  return head;
    
 Node *p1, *p2, *p3;
 p1 = head->next;
 p2 = p1->next;
 p1->next = NULL;

 while (p2)
 {
  p3 = p2->next;
  p2->next = p1;
  p1 = p2;
  p2 = p3;
 }
 head->next = p1;
 return head;
}

bool Loop(Node *head)
{
 Node *fast = head;
 Node *slow = head;

 while (fast!= NULL && fast->next != NULL)
 {
  fast = fast->next->next;
  slow = slow->next;
  if (slow == fast)
   break;
 }
 if (fast == NULL || fast->next == NULL)
  return false;
 else
     return true;
}


int main()
{
 Node *head;
 head = create();//以head为表头创建一个链表
 showList(head);//遍历以head为表头的链表
 cout << Loop(head)<<endl;
 reverse(head);
 showList(head);

 system("pause");
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值