数据结构--链表的回文结构C

本文探讨如何利用C语言判断一个链表是否具有回文结构,讲解相关算法和实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链表的回文结构

判断一个链表否为回文结构。

示例:

1->2->2->1
返回:true
bool chkPalindrome(ListNode* A) {
 // write code here
 struct ListNode* pre, * next, * cur, * fast, * slow;
 if (A == NULL) {
  return NULL;
 }
 fast = slow = A;
 while (fast && fast->next) {
  slow = slow->next;
  fast = fast->next->next;
 }
 pre = NULL;
 cur = slow;
 while (cur) {
  next = cur->next;
  cur->next = pre;
  pre = cur;
  cur = next;
 }
 cur = pre;
 while (A && cur) {
  if (A->val != cur->val) {
   return false;
  }
  A = A->next;
  cur = cur->next;
 }
 return true;}
在C语言中,判断链表是否回文可以采用递归或者双指针的方式。这里以双指针法为例来解释: **双指针法**: 1. 定义两个指针,一个`p1`初始化为头节点,另一个`p2`初始化为头节点的下一个节点,同时设置两个指针的速度,`p2`每次移动两步,`p1`每次移动一步。 2. 比较`p1`和`p2`指向的元素,如果相等,则继续比较它们的下一个节点;如果不相等,则链表不是回文,直接返回`false`。 3. 当`p1`到达链表尾部(即`p1->next == NULL`),说明已经完成了一半的比较,并且另一半与前面比较过的一样,所以链表是回文,返回`true`。 以下是一个简单的伪代码示例: ```c bool isPalindrome(struct Node* head) { struct Node* slow = head; struct Node* fast = head->next; // 如果链表只有一个元素或者空,它是回文的 if (fast == NULL || fast->next == NULL) return true; // 找到链表的中间点 while (fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; } // 反转下半部分链表并与原链表的前半部分比较 struct Node* rev = reverse(slow); // 另外一个函数用于反转链表 while (rev != NULL && head != NULL) { if (head->data != rev->data) return false; head = head->next; rev = rev->next; } return true; } // 另外的辅助函数:反转链表 struct Node* reverse(struct Node* node) { struct Node* prev = NULL; struct Node* current = node; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } return prev; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值