数据结构面试题oj练习

数据结构面试题oj练习      

数据结构面试题oj练习

oj 链接:https://leetcode-cn.com/problems/remove-linked-list-elements/description/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    
    struct ListNode* pCur = head;
    struct ListNode* pPre = NULL;
    
    while (pCur)
    {
        if (val == pCur->val)
        {
            if(head == pCur)
            {
                head = pCur->next;
                free(pCur);
                pCur = head;
            }
            else
            {
                pPre->next = pCur->next;
                free(pCur);
                pCur = pPre->next;
            }
        }
        else
        {
            pPre = pCur;
            pCur = pCur->next;
        }
    }
    return head;
}

总结: 做这道题,一定要注意返回值是什么!!!!!!!

 

数据结构面试题oj练习

 

数据结构面试题oj练习

方法一:三个指针处理:https://leetcode-cn.com/problems/reverse-linked-list/description/

数据结构面试题oj练习

struct ListNode* reverseList(struct ListNode* head) {
    
    struct ListNode* pCur = head;
    struct ListNode* pPre = NULL;
    struct ListNode* pNext = NULL;
    
    while (pCur)
    {
        pNext = pCur->next;
        pCur->next = pPre;
        pPre = pCur;
        pCur = pNext;
    }
    return pPre;
}

利用三个指针处理,其核心是pCur起指向作用,pPre和pNext仅仅作为pCur的前后结点指针使用!!!

 

方法二:头插的思想,重新弄一个链表头指针,依次将老链表的结点从后往前插入即可!!!

https://leetcode-cn.com/problems/reverse-linked-list/description/

数据结构面试题oj练习

 

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