Day13反转链表&两两交换链表中的节点&删除链表的倒数第N个节点&链表相交&环形链表II

反转链表

struct ListNode* reverseList(struct ListNode* head){
    struct ListNode* pre=NULL;
    while(head)
    {
        struct ListNode* temp=head->next;
        head->next=pre;
        pre=head;
        head=temp;
    }
    return pre;
}

两两交换链表中的节点

struct ListNode* swapPairs(struct ListNode* head){

    struct ListNode* pre;
    struct ListNode* cur;
    struct ListNode* temp;

    struct ListNode* pHead=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* shead=pHead;
    pHead->next=head;
    pre=cur=head;
    while( pre && cur->next   )
    {
        cur=cur->next;
        temp=cur->next;
        shead->next=cur;
        cur->next=pre;
        pre->next=temp;
        shead=pre;
        pre=temp;
        cur=pre;
    }

    return pHead->next;
}

删除链表的倒数第N个节点

struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    struct ListNode* sHead;
    sHead=(struct ListNode*)malloc(sizeof(struct ListNode));
    sHead->val=0;
    sHead->next=head;

    struct ListNode* slow=sHead;
    struct ListNode* fast=head;

    int i=n;
    while( fast )
    {
        if(n)
        {
            fast=fast->next;
            n--;
        }
        else
        {
            fast=fast->next;
            slow=slow->next;
        }
    }

    slow->next=slow->next->next;
    return sHead->next;

}

链表相交

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
   if(headA==NULL || headB==NULL ) return NULL;

   int lenA=0,lenB=0;
   int gap;

   struct ListNode* s;
   struct ListNode* l;
   s=headA;
   while(s)
   {
       s=s->next;
       lenA++;
   }
   s=headB;
   while(s)
   {
       s=s->next;
       lenB++;
   }

   if(lenA>lenB) 
   {
       gap=lenA-lenB;
       l=headA;
       s=headB;
   }
   else
   {
       gap=lenB-lenA;
       l=headB;
       s=headA;
   }

   while(gap--) l=l->next;

   while(l)
   {
       if(l==s) return s;
       l=l->next;
       s=s->next;
   }

   return NULL;
}

环形链表II

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

        if( slow==fast )
        {
            struct ListNode* index1 = head;
            struct ListNode* index2 = fast;
            while( index1 != index2 )
            {
                index1 = index1->next;
                index2 = index2->next;
            }
            return index1;
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值