算法学习09:判断链表是否为回文结构C++实现

题目

给定一个单链表的头结点head,请判断该链表是否为回文结构

例子

1->2->1,返回ture
1->2->2->1返回ture
15->6->15返回ture
1->2->3返回false

方法一 使用堆栈结构 额外空间复杂度O(N)

分析

将链表中的元素按顺序存入堆栈,那么栈的弹出顺序和链表的顺序刚好相反。对比栈顶元素和链表当前元素,如果不同,返回false,如果相同,弹出栈并将链表指向下一个元素,不断遍历至空,若全部相同,返回true

#include <iostream>
#include <vector>
#include <stack>

struct ListNode {
	int val;
	struct ListNode* next;
	ListNode(int x) :
			val(x), next(nullptr) {
	}
};
// need n extra space
bool isPalindrome1(ListNode* head) {
    std::stack<int> my_node_value;
    ListNode* curNode = head;
    while (curNode != nullptr) {
        my_node_value.push(curNode->val);
        curNode = curNode -> next;
    }

    while (head!= nullptr) {
        if (head -> val != my_node_value.top()) {
            return false;
        } else {
            head = head -> next;
            my_node_value.pop();
        }
    }
    return true;
}

int main()
{
    ListNode* pHead = new ListNode(1);
    pHead -> next = new ListNode(2);
    pHead -> next -> next = new ListNode(1);
    std::cout << "origin list is:" << std::endl;
    printList(pHead);
    bool is_palindrome = isPalindrome1(pHead);
    if (is_palindrome) {
        std::cout << "is palindrome" << std::endl;
    } else {
        std::cout << "not palindrome" << std::endl;
    }
    return 0;
}

方法二 利用快慢指针和堆栈结构O(N/2)

分析

使用快慢指针,快指针一次走两步,慢指针一次走一步。当快指针走完的时候,慢指针走到中间位置,将慢指针的后一半推入堆栈,出栈时元素如果和链表前半部分相同,则是回文结构。与方法一相比,当前方法只占用一半的堆栈空间,所以额外空间复杂度为)(N/2)。一个特殊的难点在于如何使慢指针在总元素个数无论是奇数还是偶数时,都恰好指在中间元素的后一个位置上。
根据快指针走完,慢指针所在的位置具体定制快慢指针
如果是奇数个,快指针走完,慢指针指在最中间的位置上;
如果是偶数个,快指针走完,慢指针指在中点的前一个或后一个元素上。

// need n/2 extra space
bool isPalindrome2(ListNode* head) {
    if (head == nullptr || head -> next == nullptr) {
        return true;
    }
    std::stack<int> my_node_value;
    ListNode* slowNode = head -> next;
    ListNode* fastNode = head;
    while (fastNode -> next != nullptr && fastNode -> next -> next != nullptr) {    // get the middle node
        slowNode = slowNode -> next;
        fastNode = fastNode -> next -> next;
    }
    while (slowNode != nullptr) {
        my_node_value.push(slowNode -> val);
        slowNode = slowNode -> next;
    }
    while (!my_node_value.empty()) {   // here we can't use the condition: head != nullptr
        if (head -> val != my_node_value.top()) {
            return false;
            break;
        } else {
            head = head -> next;
            my_node_value.pop();
        }
    }
    return true;
}

完整代码

#include <iostream>
#include <vector>
#include <stack>

struct ListNode {
	int val;
	struct ListNode* next;
	ListNode(int x) :
			val(x), next(nullptr) {
	}
};
// need n/2 extra space
bool isPalindrome2(ListNode* head) {
    if (head == nullptr || head -> next == nullptr) {
        return true;
    }
    std::stack<int> my_node_value;
    ListNode* slowNode = head -> next;
    ListNode* fastNode = head;
    while (fastNode -> next != nullptr && fastNode -> next -> next != nullptr) {    // get the middle node
        slowNode = slowNode -> next;
        fastNode = fastNode -> next -> next;
    }
    while (slowNode != nullptr) {
        my_node_value.push(slowNode -> val);
        slowNode = slowNode -> next;
    }
    while (!my_node_value.empty()) {   // here we can't use the condition: head != nullptr
        if (head -> val != my_node_value.top()) {
            return false;
            break;
        } else {
            head = head -> next;
            my_node_value.pop();
        }
    }
    return true;
}

int main()
{
    ListNode* pHead = new ListNode(1);
    pHead -> next = new ListNode(2);
    pHead -> next -> next = new ListNode(1);
    std::cout << "origin list is:" << std::endl;
    printList(pHead);
    bool is_palindrome = isPalindrome2(pHead);
    if (is_palindrome) {
        std::cout << "is palindrome" << std::endl;
    } else {
        std::cout << "not palindrome" << std::endl;
    }
    return 0;
}

方法三 利用快慢指针和逆序一半链表(额外空间复杂度O(N))

分析

总体分为四步

  1. 找到中间位置,当链表元素为奇数个时,方法二的慢指针停在之间靠右一个位置,方法三的慢指针位于最中间。(这样设计后从慢指针的下一个位置开始就是反转部分)
  2. 逆序后半部分,采用反转链表的方法
  3. 进行比较
  4. 重排恢复链表,依旧是一个逆序的过程
代码
//使用快慢指针但不用辅助空间判断是否是回文链表
#include<iostream>


using namespace std;
typedef struct listnode
{
	int val ;
	listnode *next;
}*List;

bool IsPalindromeList(List head)
{
	head = head->next;
	if (head == NULL|| head->next == NULL) 
		return true;
	List p1,p2,p1_pre = NULL;
	p2 = head;//快指针
	p1 = head;//慢指针

	while(p2->next != NULL)
	{
		p1_pre = p1;
		p2 = p2->next;
		p1 = p1->next;
		if(p2->next == NULL)
		{
			break;
		}
		p2 = p2->next;

	}
	//逆序
	List cur = p1;
	List pre = NULL;
	
	while(cur!=NULL)
	{
		List temp = cur->next;
		cur->next = pre;
		pre = cur;
		cur = temp;
	}

	//比较
	bool res = true;
	cur = pre;//pre是保留的最后一个数
	while(cur != NULL)
	{
		if(cur->val != head->val)
		{
			res = false;
			break;
		}
		cur = cur->next;
		head = head->next;
	}

	//重排
	cur = pre;
	pre = NULL;
	while(cur!=NULL && cur!= p1_pre)
	{
		List temp = cur->next;
		cur->next = pre;
		pre = cur;
		cur = temp;
	}

	return res;
}

List insert(List head,int num)
{
	//初始化新节点
	List p = (List)malloc(sizeof(listnode));
	p->val = num;
	p->next = NULL;

	//找到链表末尾
	List r = head;
	while(r->next != NULL)
	{
		r = r->next; 
	}
	//将新节点加入链表
	r->next = p;
	return head;
}

List MakeEmpty()
{
	List head = (List)malloc(sizeof(listnode));
	head->next = NULL;
	return head;
}

int main()
{
	List head = MakeEmpty();
	insert(head,1);
	insert(head,2);
	insert(head,3);
	insert(head,4);
	insert(head,4);
	insert(head,3);
	insert(head,2);
	insert(head,0);

	cout<<IsPalindromeList(head);
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值