1.删除链表中值为v的结点
- 保存值为v节点的前一个节点
- 释放置为v的节点
- 保存的节点指向值为v节点的下一个节点地址
void SListRemove(SList *s, SListDataType v) {
if (s->first == NULL) {
return;
}
if (s->first->value == v) {
Node *second = s->first->next; //记录原来的第二个结点
free(s->first);//释放第一个结点空间
s->first = second;//原来的第二个变为第一个
}
else {
Node *c = s->first;
while (c->next != NULL) {
if (c->next->value == v) {
Node *next = c->next;
c->next = c->next->next;
free(next);
return;
}
c = c->next;
}
}
}
2.链表逆置(1)
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode *result = NULL;
struct ListNode *c = head;
while (c != NULL) {
struct ListNode *next = c->next;
c->next = result;
result = c;
c = next;
}
return result;
}

3.合并两个有序链表,合并后仍然有序
- 如果有一个链表为空,则返回另一个链表
- 比较两个链表节点值的大小,小的尾插到新链表中
- 比较完,一个链表若仍有剩余,则全部尾插到新链表中
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode *l2) {
if (l1 == NULL) { return l2; }
if (l2 == NULL) { return l1; }
struct ListNode *c1 = l1;
struct ListNode *c2 = l2;
struct ListNode *result = NULL;//新链表的第一个结点
struct ListNode *tail = NULL;//新链表的最后一个结点
while (c1 != NULL && c2 != NULL) {
if (c1->val <= c2->val) {
if (tail != NULL) {
tail->next = c1;
tail = c1;
}else{
result = tail = c1;
}
c1 = c1->next;
}
else {
if (tail != NULL) {
tail->next = c2;
tail = c2;
}
else {
result = tail = c2;
}
c2 = c2->next;
}
}
if (c1 != NULL) {
tail->next = c1;
}
if (c2 != NULL) {
tail->next = c2;
}
return result;
}
4.查找单链表的中间结点,偶数返回第二个 (快慢指针)
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode *fast = head;
struct ListNode *slow = head;
while (fast != NULL) {
fast = fast->next;
if (fast == NULL) {
break;
}
slow = slow->next;
fast = fast->next;
}
return slow;
}
这篇博客介绍了如何进行链表操作,包括删除指定值的节点、链表逆置、合并两个有序链表并保持有序,以及利用快慢指针找到单链表的中间或第二个中间节点。
1030

被折叠的 条评论
为什么被折叠?



