牛客网--关于回文链表

101 篇文章 0 订阅
67 篇文章 0 订阅

牛客网--关于回文链表

题目描述

请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。

测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false

代码

import java.util.*;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Palindrome {
    public boolean isPalindrome(ListNode pHead) {
        // write code here
        if(pHead == null || pHead.next == null)
            return true;
        
        ListNode newList = new ListNode(-1);
        ListNode curr = pHead;
        while(curr != null)
        {
            ListNode newNode = new ListNode(curr.val);
            newNode.next = newList.next;
            newList.next = newNode;
            curr = curr.next;
        }
        
        newList = newList.next;
        while(pHead != null || newList != null)
        {
            if(pHead.val != newList.val)
                return false;
            pHead = pHead.next;
            newList = newList.next;
        }
        
        if(pHead == null && newList == null)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
  • 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、付费专栏及课程。

余额充值