力扣基础链表题总结
Posted Billy Miracle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了力扣基础链表题总结相关的知识,希望对你有一定的参考价值。
237. 删除链表中的节点
思路:
将所给结点值改变,再将结点next指向下下个结点,就完成了要求。
One Possible Answer:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
19. 删除链表的倒数第 N 个结点
思路:
双指针,找到结点
One Possible Answer:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
if (head == NULL) {
return head;
}
struct ListNode* newhead = (struct ListNode*)malloc(sizeof(struct ListNode));
newhead->val = 0, newhead->next = head;
struct ListNode* first = head, * second = newhead;
for (int i = 0; i < n; ++i) {
first = first->next;
}
while (first) {
first = first->next;
second = second->next;
}
second->next = second->next->next;
struct ListNode* ans = newhead->next;
free(newhead);
return ans;
}
206. 反转链表
思路:
从头一个个逆向建链,最后返回新链的头
One Possible Answer:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode Node;
struct ListNode* reverseList(struct ListNode* head) {
Node* pre = NULL, * cur = head;
while (cur) {
Node* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
21. 合并两个有序链表
思路:
建新链,一个个判断,把小的接在后面。
One Possible Answer:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)), * t=head;
while (l1 && l2) {
if (l1->val < l2->val) {
t->next = l1;
l1 = l1->next;
} else {
t->next = l2;
l2 = l2->next;
}
t = t->next;
}
if (l1) {
t->next = l1;
} else if (l2) {
t->next = l2;
}
return head->next;
}
234. 回文链表
思路:
把数字取到数组中再判断
One Possible Answer:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode* head) {
int vals[100000], l = 0;
while (head != NULL) {
vals[l++] = head->val;
head = head->next;
}
for (int i = 0, j = l - 1; i < j; ++i, --j) {
if (vals[i] != vals[j]) {
return false;
}
}
return true;
}
141. 环形链表
思路:
快慢指针
One Possible Answer:
bool hasCycle(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return false;
}
struct ListNode* slow = head;
struct ListNode* fast = head->next;
while (slow != fast) {
if (fast == NULL || fast->next == NULL) {
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}
以上是关于力扣基础链表题总结的主要内容,如果未能解决你的问题,请参考以下文章