码迷,mamicode.com
首页 > 其他好文 > 详细

我要好offer之 链表大总结

时间:2014-08-13 18:37:17      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   for   ar   div   

单链表是一种递归结构,可以将单链表看作特殊的二叉树(我把它叫做一叉树)

单链表的定义:

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

1. O(1)时间删除结点

ListNode* DeleteNode(ListNode* pHead, ListNode* deletedNode) {
    assert(pHead != NULL && deletedNode != NULL);
    ListNode newHead(-1);
    newHead.next = pHead;
    if (pHead == deletedNode) {
        newHead->next = pHead->next;
        delete deletedNode;
        deketedNode = NULL;
        return newHead.next;
    } else {
        if (deleteNode->next == NULL) {
            ListNode* cur = pHead;
            while (cur->next != deleteNode) {
                cur = cur->next;
            }
            cur->next = NULL;
            delete deletedNode;
            deletedNode = NULL;
            return newHead.next;
        } else {
            ListNode* nextNode = deletedNode->next;
            deletedNode->val = nextNode->val;
            deletedNode->next = nextNode->next;
            delete nextNode;
            nextNode = NULL;
            return newHead.next;
        }
    }
}

 

2. 单链表反转

ListNode* ReverseList(ListNode* pHead) {
    if (pHead == NULL || pHead->next == NULL) {
        return pHead;
    }
    ListNode* tail = pHead;
    ListNode* cur = pHead->next;
    while (cur != NULL) {
        ListNode* nextNode = cur->next;
        cur->next = pHead;
        pHead = cur;
        cur = nextNode;
    }
    tail->next = NULL;
    return pHead;
}

 

3. 单链表倒数第k个结点

ListNode* KthNode(ListNode* pHead, int k) {
    assert(pHead != NULL && k > 0);
    ListNode* first = pHead;
    ListNode* second = pHead;
    while (first != NULL && k > 0) {
        first = first->next;
        --k;
    }
    if (first == NULL) {
        if (k == 0) {
            return pHead;
        } else {
            return NULL;
        }
    }
    while (first != NULL) {
        first = first->next;
        second = second->next;
    }
    return second;
}

 

4. 单链表反转部分区间

5. 单链表快速排序的一趟划分

6. 单链表去掉重复元素

7. 单链表旋转

8. 单链表成对交换节点

9. 有序单链表归并排序

10. 单链表加法运算

11. 单链表是否存在环,环的位置

12. 两个单链表的第一个公共结点

我要好offer之 链表大总结,布布扣,bubuko.com

我要好offer之 链表大总结

标签:style   blog   http   color   io   for   ar   div   

原文地址:http://www.cnblogs.com/wwwjieo0/p/3910605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!