回文链表(todo:优化为空间O1)

回文链表
请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnv1oc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

# 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: ListNode) -> bool:

        cnt = 0 

        record = []

        while head:

            cnt+=1

            record.append(head.val)

            head = head.next

        for i in range(cnt//2):

            if record[i]==record[cnt-i-1]:

                continue

            else:

                return False

        return True

 

执行结果:

通过

显示详情

执行用时:752 ms, 在所有 Python3 提交中击败了17.22%的用户

内存消耗:47.6 MB, 在所有 Python3 提交中击败了16.64%的用户

           

题目描述: 给定一个链表,判断该链表是否是回文结构。 例如: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、付费专栏及课程。

余额充值