标签 链表 下的文章

题目链接:反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

方法一:反转链表
/**

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

class Solution {
public:

ListNode* reverseList(ListNode* head) {
    if (head == NULL || head->next == NULL) return head;
    ListNode* ans;
    ans = nullptr;
    while (head) {
        ListNode* t = head->next;
        head->next = ans;
        ans = head;
        head = t;
    }
    return ans;
}

};

题目链接:相交链表

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

方法一:哈希表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        unordered_set<ListNode *> m;
        while (headA) {
            m.insert(headA);
            headA = headA->next;
        }
        while (headB) {
            if (m.count(headB)) {
                return headB;
            }
            headB = headB->next;
        }
        return NULL;
    }
};