Palindrome Linked List

解法一:

一次遍历。装入vector,然后再一次遍历推断回文。

时间复杂度O(n)。空间复杂度O(n)

解法二:

找到链表中点,拆分后。逆转后半个链表,然后两个链表同一时候顺序遍历一次。

若链表长度为奇数。最末尾的元素能够忽略。

时间复杂度O(n),空间复杂度O(1)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 int LengthList(struct ListNode* head);
 struct ListNode* reverseList(struct ListNode* head);
bool isPalindrome(struct ListNode* head)
{

   if(head==NULL||head->next==NULL)
     return true;
	//旋转后一半。。

。可是改变了这个数据的结构...?

int length=LengthList(head); int mid=(length+1)/2; struct ListNode* pCurrlent=head; //O(1) for (int i=0;i<mid;i++) { pCurrlent=pCurrlent->next; } //最后一个为中点那个 struct ListNode* newMidHead=reverseList(pCurrlent); pCurrlent=head; struct ListNode* pCurrlentMid=newMidHead; for (int i=0;i<(length/2);i++) { if (pCurrlent->val!=pCurrlentMid->val) { return false; } pCurrlent=pCurrlent->next; pCurrlentMid=pCurrlentMid->next; } return true; } int LengthList(struct ListNode* head) { if(head==NULL) return 0; int length=0; struct ListNode* pCurrent=head; while(pCurrent!=NULL) { length++; pCurrent=pCurrent->next; } //free(pCurrent); return length; } struct ListNode* reverseList(struct ListNode* head) { struct ListNode* newhead; newhead=NULL; //这样就不须要翻转了 if (head==NULL||head->next==NULL) { return head; } struct ListNode* pCurrent=head; //一样的点 while(pCurrent!=NULL) { struct ListNode* tmp=pCurrent; pCurrent=pCurrent->next; tmp->next=newhead; //把节点放在节点前面,插入到链表的最前端 newhead=tmp; } return newhead; }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值