数据结构与算法分析——链表、栈、队列

链表

声明

struct ListNode{

    ElementType Element;

    ListNode *next;

}

void insert(ElementType e, ListNode *List, ListNode *Position){

    if(List == NULL) return;

    ListNode *L;

    L = (struct ListNode*)malloc(sizeof(ListNode));

    L->Element = e;

    L->next = Position->next;

    Position->next = L;

}

ListNode* findPre(ElementType e, ListNode *List){

    if( List == NULL) return NULL;

    ListNode *p = List;

    while(p->next != NULL && p->next->Element != e)

       p = p->next;

    return p;

}

ListNode* find(ElementType e, ListNode *List){

    if( List == NULL) return NULL;

    ListNode *p = List->next; // List有表头

    while(p != NULL && p->Element != e)

       p = p->next;

    return p;

}

void delete(ElementType e, ListNode *List){

    if(List == NULL) return;

    ListNode *P = findPre(e,List);

    if(P == NULL)

        return;

    if(P->next != NULL){

        ListNode *tmp = P->next;

        P->next = tmp->next;

        free(tmp);

    }

}

快慢节点

1.从中间讲链表分为两段,得到中心节点。

   // 链表长为N,当快节点的位置为2*(N/2),慢节点的位置为N/2。

ListNode *findMiddle(ListNode *List){

    ListNode *fast = List;

    ListNode *slow = List;

    while(fast->next != NULL && fast->next->next != NULL){

        slow = slow->next;

        fast = fast->next->next;

    }

    return slow; //slow->next就是后半段

}

2.查找环节点的位置

 ListNode *detectCycle(ListNode *head) {
        if(head == NULL) return NULL;
        ListNode *fast = head;
        ListNode *slow = head;
        //fast = 2*slow
        while(fast->next != NULL && fast->next->next != NULL){
            fast = fast->next->next;
            slow = slow->next;
            if(slow == fast)//在环上的第b个节点相遇
                break;
        }
        if(fast->next == NULL || fast->next->next == NULL)
            return NULL;
        //设环长b+c,环初始节点为链表上第a个节点
        //fast.position = a+n*(b+c)+b = 2*(a+b) = 2*slow.position
        //==> a = n*(b+c)-b;
        //fast.position + 2a = a+n*(b+c)+b+2n*(b+c)-b = a+3n*(b+c)回到环初始节点
        slow = head;
        while(slow != fast){
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }

你可能感兴趣的:(数据结构与算法)