算法-链表

一、链表反转

解法:始终将当前结点的next指针指向其前一个结点。借助两个辅助指针pre、next。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        //如果没有链表没有结点或只有一个结点就直接返回。
		if (pHead == NULL || pHead->next == NULL)
		{
			return pHead;
		}
        //pre 保存cur结点的前一个结点,默认为NULL
		ListNode* pre = NULL;
		ListNode* cur = pHead;
		while(cur != NULL)
		{
            //next 保存当前结点的下一结点
			ListNode *next = cur ->next;
			cur->next = pre;
			pre = cur;
			cur = next;
		}
        //pre一定是新链表的头结点。
		return pre;
    }
};

二、合并两个有序的链表

解法:

1.首先判断两个有序链表是否为空,如果是返回另一个链表

2.定义pHead3作为新链表的头,然后根使用合并两个有序数组相同的算法合并两个有序链表。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        if (pHead1 == NULL)
			return pHead2;
		if (pHead2 == NULL)
			return pHead1;

		ListNode *pHead3=NULL,*p=NULL;
		while(pHead1 != NULL && pHead2 != NULL)
		{
			if (pHead1->val < pHead2->val)
			{
				if (pHead3 == NULL)
				{
					pHead3 = pHead1;
					p = pHead1;
				}else{
					p->next = pHead1;
					p = p->next;
				}
				pHead1 = pHead1->next;
			}else
			{
				if (pHead3 == NULL)
				{
					pHead3 = pHead2;
					p = pHead2;
				}else{
					p->next = pHead2;
					p = p->next;
				}
				pHead2 = pHead2->next;
			}
		}

		while(pHead1 != NULL)
		{
			p->next = pHead1;
			p = p->next;
			pHead1 = pHead1->next;
		}
		while(pHead2 != NULL)
		{
			p->next = pHead2;
			p = p->next;
			pHead2 = pHead2->next;
		}
		return pHead3;
    }
};

三、判断链表是否有环

解法:使用快慢指针,指针p1每次向后移动一个单位,指针p2每次向后移动两个单位,如果存在环,则p2会再次与p1相等。(类比操场跑步,跑的快的迟早会“追上”跑的慢的)。

#include <iostream>

using namespace std;

// Definition for singly-linked list.
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:
    bool hasCycle(ListNode *head)
    {
        ListNode *p1 = head;
        ListNode *p2 = head;

        while (p1 != NULL && p2 != NULL)
        {
            p1 = p1->next;
            if (p2->next == NULL)
            {
                return false;
            }
            p2 = p2->next->next;

            //判断
            if (p2 == p1)
            {
                return true;
            }
        }

        return false;
    }
};

void test01()
{
    //{3,2,0,-4},1

    ListNode n0(3);
    ListNode n1(2);
    ListNode n2(0);
    ListNode n3(-4);

    n0.next = &n1;
    n1.next = &n2;
    n2.next = &n3;
    n3.next = &n1;

    cout << Solution().hasCycle(&n0) << endl;
}

void test02()
{
    //{1},-1

    ListNode n0(-1);
    cout << Solution().hasCycle(&n0) << endl;
}

void test03()
{
    // {-1,-7,7,-4,19,6,-9,-5,-2,-5},6
    ListNode n0(-1);
    ListNode n1(-7);
    ListNode n2(7);
    ListNode n3(-4);
    ListNode n4(19);
    ListNode n5(6);
    ListNode n6(-9);
    ListNode n7(-5);
    ListNode n8(-2);
    ListNode n9(-5);

    n0.next = &n1;
    n1.next = &n2;
    n2.next = &n3;
    n3.next = &n4;
    n4.next = &n5;
    n5.next = &n6;
    n6.next = &n7;
    n7.next = &n8;
    n8.next = &n9;
    n9.next = &n6;

    cout << Solution().hasCycle(&n0) << endl;
}

int main()
{
    test01();
    test02();
    test03();

    return 0;
}

四、链表中倒数k个结点

解法一:时间复杂度 O(n)、空间复杂度:O(n)。

使用数组记录所有结点,这样可以知道所有结点的个数,并且很容易的得到倒数第K个结点。

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* FindKthToTail(ListNode* pHead, int k) {
        // write code here
        ListNode *p = pHead;
        vector<ListNode *> v;
        while (p != NULL)
        {
            v.push_back(p);
            p = p->next;
        }

        if (k == 0 || k > v.size())
        {
            return NULL;
        }

        return v[v.size() - k];
    }
};

解法二:时间复杂度 O(n)、空间复杂度:O(1)。

使用两个指针p、q,先让两个最大距离达到K,然后同步向后移动。

#include <iostream>

using namespace std;

// Definition for singly-linked list.
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param pHead ListNode类
     * @param k int整型
     * @return ListNode类
     */
    ListNode *FindKthToTail(ListNode *pHead, int k)
    {

        ListNode *p = pHead;
        ListNode *q = pHead;

        for (int i = k; i > 0; i--)
        {
            if (q == NULL)
            {
                return NULL;
            }

            q = q->next;
        }
        while (q)
        {
            p = p->next;
            q = q->next;
        }
        return p;
    }
};

int main()
{
    ListNode n0(1);
    ListNode n1(2);
    ListNode n2(3);
    ListNode n3(4);
    ListNode n4(5);

    n0.next = &n1;
    n1.next = &n2;
    n2.next = &n3;
    n3.next = &n4;

    ListNode *p = Solution().FindKthToTail(&n0, 2);
    while (p != NULL)
    {
        cout << p->val << " ";
        p = p->next;
    }
    cout << endl;

    return 0;
}

五、两个链表的第一个公共结点

解法1:如果两个人以相同速度,不同路程跑步,如何让他们同时到达终点,答案就是:将对方的路程也加到自己的路程上来。

 
 

ListNode *FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2)
    {
        ListNode *p = pHead1;
        ListNode *q = pHead2;

        while (p != q)
        {
            p = (p == NULL) ? pHead2 : p->next;
            q = (q == NULL) ? pHead1 : q->next;
        }
        return p;
    }

        

解法2:先进行两次循环,得出两个链表的长度。再让长度链表先走k的长度(k为长度差),然后两个指针一起走,直到相等(都为NULL也算相等)。

ListNode *FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2)
    {
        ListNode *p = pHead1;
        ListNode *q = pHead2;
        int len1 = 0, len2 = 0;
        while (p != NULL)
        {
            len1++;
            p = p->next;
        }
        while (q != NULL)
        {
            len2++;
            q = q->next;
        }
        p = pHead1, q = pHead2;
        if (len1 >= len2)
        {
            for (int i = 0; i < len1 - len2; i++)
            {
                p = p->next;
            }
        }
        else
        {
            for (int i = 0; i < len2 - len1; i++)
            {
                q = q->next;
            }
        }
        while (p != NULL && q != NULL && p != q)
        {
            p = p->next;
            q = q->next;
        }
        return p;
    }

        

六、判断链表是否为回文序列

所谓回文序列就是正序和逆序相同的字符串:如a、aa、aba、abba

解法一:由于链表只能单向遍历,所以遍历链表,将所有值放入数组中,然后判断数组是否为回文数组。 时间复杂度:O(n)、空间复杂度:O(n)


class Solution {
public:
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    bool isPail(ListNode* head) {
        vector<int> v;
        ListNode* p =head;
        while(p != NULL)
        {
            v.push_back(p->val);
            p=p->next;
        }
        int i=0;
        int j=v.size()-1;

        while(i<j)
        {
            if (v[i] != v[j])
            {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
};

解法二:从中间将链表一分为二、并将链表的一半反转,然后顺序比较。至于怎么将链表一分为二,可是根据链表长度、也可以使用快慢指针。 时间复杂度:O(n)、空间复杂度:O(1)

#include <iostream>
#include <vector>

using namespace std;

struct ListNode {
public:
    int val;
    struct ListNode *next;
    ListNode(int _val):val(_val),next(NULL){}
};


class Solution {
public:
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    bool isPail(ListNode* head) {
        if (head == NULL)
        {
            return false;
        }

        ListNode* s = head;
        ListNode* f = head;

        while(f != NULL && f->next != NULL && f->next->next != NULL)
        {
            s = s->next;
            f = f->next->next;
        }
        bool jishu = false;
        if (f->next == NULL)
        {
            jishu = true;
        }
        
        if (jishu)
        {
            ListNode* end = s;
            ListNode* start1 = head;
            ListNode* start2 = s->next;
            start2 = reverse(start2);

            while(start1 != end && start2 !=NULL)
            {
                if (start1->val != start2->val)
                {
                    return false;
                }
                start1 = start1->next;
                start2 = start2->next;
            }
            return true;
        }else
        {
            ListNode* end = s->next;
            ListNode* start1 = head;
            ListNode* start2 = s->next;
            start2 = reverse(start2);

            while(start1 != end && start2 != NULL)
            {
                if (start1->val != start2->val)
                {
                    return false;
                }
                start1 = start1->next;
                start2 = start2->next;
            }
            return true;
        }
    }
    ListNode* reverse(ListNode* head)
    {
        ListNode*p = head;
        ListNode*pre =NULL;
        while(p != NULL)
        {
            ListNode* next=p->next;
            p->next = pre;
            pre = p;
            p = next;
        }
        return pre;
    }
};

void test01();
void test02();
void test03();
void test04();
void test05();
void test06();

int main(){
    test01();
    test02();
    test03();
    test04();
    test05();
    test06();
    return 0;
}

void test01()
{ 
    bool ret = Solution().isPail(NULL);
    cout<<ret<<endl;
}

void test02()
{
    ListNode n0(1);
  
    bool ret = Solution().isPail(&n0);
    cout<<ret<<endl;
}

void test03()
{
    ListNode n0(1);
    ListNode n1(1);
    n0.next = &n1;
  
    bool ret = Solution().isPail(&n0);
    cout<<ret<<endl;
}

void test04()
{
    ListNode n0(1);
    ListNode n1(2);
    ListNode n2(1);
    n0.next = &n1;
    n1.next = &n2;
  
    bool ret = Solution().isPail(&n0);
    cout<<ret<<endl;
}

void test05()
{
    ListNode n0(1);
    ListNode n1(2);
    ListNode n2(2);
    ListNode n3(1);
    n0.next = &n1;
    n1.next = &n2;
    n2.next = &n3;
  
    bool ret = Solution().isPail(&n0);
    cout<<ret<<endl;
}

void test06()
{
    ListNode n0(1);
    ListNode n1(2);
    ListNode n2(2);
    ListNode n3(3);
    n0.next = &n1;
    n1.next = &n2;
    n2.next = &n3;
  
    bool ret = Solution().isPail(&n0);
    cout<<ret<<endl;
}

七、有序链表去重

解法:略。

class Solution
{
public:
    /**
     *
     * @param head ListNode类
     * @return ListNode类
     */
    ListNode *deleteDuplicates(ListNode *head)
    {
        ListNode *p = head;
        while (p != NULL)
        {
            ListNode *back = p->next;
            if (back != NULL && back->val == p->val)
            {
                p->next = back->next;
                continue;
                // free(next)
            }
            p = p->next;
        }
        return head;
        // write code here
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值