Insertion Sort List && Remove Duplicates from Sorted List II && Intersection of Two Linked Lists

来源:互联网 发布:ubuntu撤销命令 编辑:程序博客网 时间:2024/05/01 08:10

Insertion Sort List

1、插入排序,用了个头节点。

2、天气太冷,冻得写出来的代码就是翔。

    ListNode *insertionSortList(ListNode *head) {        if (head == NULL)            return NULL;        ListNode *p = head->next;        ListNode *newhead = new ListNode(0);        newhead->next = head;        head->next = NULL;        ListNode *insp;        while (p != NULL) {            ListNode *q = p;            p = p->next;            insp = newhead;            while (insp->next != NULL && q->val > insp->next->val) {                insp = insp->next;            }            if (insp->next == NULL) {                insp->next = q;                q->next = NULL;            }            else {                q->next = insp->next;                insp->next = q;            }        }        insp = newhead;        newhead = newhead->next;        free(insp);        return newhead;    }


Remove Duplicates from Sorted List II

1、建立头节点,设立标志。

    ListNode *deleteDuplicates(ListNode *head) {        ListNode *newhead = new ListNode(0);        newhead->next = head;        bool flag = false;        ListNode *p = newhead->next;        ListNode *q = newhead;        ListNode *temp;        while (p != NULL) {            while (p->next != NULL && p->val == p->next->val) {                flag = true;                temp = p->next;                p->next = p->next->next;                free(temp);            }            if (flag) {                flag = false;                temp = p;                p = p->next;                free(temp);                q->next = p;            }            else {                q = p;                p = p->next;            }        }                temp = newhead;        newhead = newhead->next;        free(temp);        return newhead;    }


Intersection of Two Linked Lists

1、找到两个链表合并的点。

2、两个指针,第一遍找出长度,第二遍找出相同的点。

    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {        int lenA = 0, lenB = 0;        ListNode *pA = headA, *pB = headB;        while (pA != NULL) {            pA = pA->next;             lenA++;        }        while (pB != NULL) {            pB = pB->next;             lenB++;        }        int len = lenA > lenB ? lenA - lenB : lenB - lenA;        pA = headA;        pB = headB;        if (lenA > lenB) {            while (len--)                pA = pA->next;        }        else {            while (len--)                pB = pB->next;        }        while (pA != NULL && pB != NULL && pA != pB) {            pA = pA->next;            pB = pB->next;        }        return pA;    }


0 0
原创粉丝点击