c语言完成以下链表4个典型应用的解题思路和代码撰写 1、链表原地逆置 2、求链表的中间(中左)结点 3、求链表的倒数第k个结点 4、2个有序链表的合并
时间: 2024-10-27 22:02:06 浏览: 25
1. **链表原地逆置**:
解题思路:遍历链表,每次将当前节点的下一个节点指向前一个节点,最后指向头节点的下一个节点设为NULL。
C语言代码示例:
```c
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* prev = NULL;
struct ListNode* current = head;
while (current != NULL) {
struct ListNode* nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
return prev; // 新头节点就是原尾节点
}
```
2. **求链表的中间结点**:
解题思路:双指针法,快慢指针分别移动,当快指针到达尾部时,慢指针正好到中间位置。
C语言代码示例:
```c
struct ListNode* findMiddleNode(struct ListNode* head) {
if (head == NULL || head->next == NULL) return head;
struct ListNode* slow = head;
struct ListNode* fast = head->next;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
```
3. **求链表的倒数第k个结点**:
解题思路:先遍历链表找到长度,然后从头开始遍历k次即可。
C语言代码示例:
```c
struct ListNode* findKthToTail(struct ListNode* head, int k) {
int len = 0;
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = head;
for (struct ListNode* node = dummy; node != NULL; node = node->next)
len++;
node = dummy;
for (int i = 0; i < len - k; i++)
node = node->next;
free(dummy);
return node;
}
```
4. **两个有序链表的合并**:
解题思路:创建一个新的链表并按顺序连接两个已排序链表。
C语言代码示例:
```c
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
if (l1->val <= l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
```
阅读全文