【hot100篇-python刷题记录】【回文链表】

R7-链表篇

思路: 

转回文数组法

链表转数组,再使用双指针判断是不是回文数组即可。

wkao?!根本不用双指针判断是否回文数组,只需要倒序判断布尔值即可。(牛啊牛啊)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        ret=[]
        cur=head
        while cur is not None:
            ret.append(cur.val)
            cur=cur.next
        return ret==ret[::-1]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
题目描述: 给定一个链表,判断该链表是否是回文结构。 例如:1->2->3->2->1 是回文链表。 1->2->3->3->2->1 是回文链表。 输入: 待判断的整数链表。 输出: 若是回文结构则输出1,否则输出0。 代码实现: ```c #include <stdio.h> #include <stdlib.h> //定义链表节点 typedef struct ListNode{ int val; struct ListNode *next; }ListNode; //创建链表 ListNode* createList(int n){ ListNode *head = (ListNode*)malloc(sizeof(ListNode)); ListNode *p = head; for(int i=1; i<=n; i++){ ListNode *newNode = (ListNode*)malloc(sizeof(ListNode)); newNode->val = i; p->next = newNode; p = p->next; } return head->next; } //反转链表 ListNode* reverseList(ListNode *head){ ListNode *prev = NULL; ListNode *cur = head; while(cur != NULL){ ListNode *next = cur->next; cur->next = prev; prev = cur; cur = next; } return prev; } //判断回文链表 int isPalindrome(ListNode* head){ if(head == NULL || head->next == NULL){ return 1; } ListNode *slow = head; ListNode *fast = head; while(fast->next != NULL && fast->next->next != NULL){ slow = slow->next; fast = fast->next->next; } ListNode *mid = slow; ListNode *secondHead = reverseList(mid->next); ListNode *p1 = head; ListNode *p2 = secondHead; int res = 1; while(p2 != NULL){ if(p1->val != p2->val){ res = 0; break; } p1 = p1->next; p2 = p2->next; } mid->next = reverseList(secondHead); return res; } int main(){ //创建链表 ListNode *head = createList(5); //打印链表 ListNode *p = head; while(p != NULL){ printf("%d ",p->val); p = p->next; } printf("\n"); //判断回文链表 int res = isPalindrome(head); printf("%d\n",res); return 0; } ``` 注释详细,逻辑清晰。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值