每日一题:链表oj题

1.找链表倒数第k个节点

class Solution {
public: 
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
   if(NULL==pListHead||k==0)
   return NULL;
    ListNode* fast=pListHead;
    ListNode* slow=pListHead;
    while(k--)
    {
        if(NULL==fast)
            return NULL;
        fast=fast->next;
    }
        while(fast)
        {
           fast=fast->next;
            slow=slow->next;
        }

    return slow;
}
};

2.单链表的逆置

typedef  struct ListNode ListNode;
struct ListNode* reverseList(struct ListNode* head){
ListNode* cur=head;
ListNode* prev=NULL;
ListNode* next=NULL;
while(cur)
{
    next=cur->next;
    cur->next=prev;
    prev=cur;
    cur=next;
}
return prev;
}

3.将两个有序链表合并成一个

typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    if(NULL==l1)
       return l2;
    if(NULL==l2)
       return l1;
    ListNode newHead; 
    ListNode* cur1=l1;
    ListNode* cur2=l2;
    ListNode* tailNode=&newHead;
    
    while(cur1&&cur2)
    {
        if(cur1->val<cur2->val)
        {
            tailNode->next=cur1;
            cur1=cur1->next;
        }
        else
        {
            tailNode->next=cur2;
            cur2=cur2->next;
        }
        tailNode=tailNode->next;
    }
    if(cur1)
       tailNode->next=cur1;
    else
       tailNode->next=cur2;
    return newHead.next;
}

4.编写一个程序,找到两个单链表相交的起始节点。
结题要领:
1>确定是否相交:确定最后一个节点是否相同
2>求交点:第一个公共交点

typedef struct ListNode ListNode;
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    if(NULL==headA||NULL==headB)
    return NULL;
    ListNode* curA=headA;
    int countA=1;
    while(curA->next)
    {
     countA++;
     curA=curA->next;   
    }
    ListNode* curB=headB;
    int countB=1;
    while(curB->next)
    {
        countB++;
        curB=curB->next;
    }
    if(curA!=curB)
    return NULL;
    curA=headA;
    curB=headB;
    int gap=countA-countB;
    if(gap>0)
    while(gap--)
    {
        curA=curA->next;  
    }
    else{
    while(gap++)
    {
        curB=curB->next;
    }
    }
    while(curA!=curB)
    {
        curA=curA->next;
        curB=curB->next;
    }
    return curA;
}

5.给定一个链表,判断链表中是否有环。

 typedef struct ListNode ListNode;
bool hasCycle(struct ListNode *head) {
    ListNode* fast=head;
    ListNode* slow=head;
    while(fast&&fast->next)
    {
        fast=fast->next->next;
        slow=slow->next;

        if(fast==slow)
        return true;
    }
    return false;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值