知识储备:03链表:链表之哑节点的使用

来源:互联网 发布:07版excel编程入门教程 编辑:程序博客网 时间:2024/05/06 06:59

要对头结点进行操作时,考虑创建哑节点dummy,使用dummy->next表示真正的头节点。这样可以避免处理头节点为空的边界问题。

1.给定一个链表和x,对链表排序使所有小于x的节点出现在大于或等于x的节点的前面。

代码如下:

#include <iostream>using namespace std;
/*链表之哑节点的使用2-17-8-22*/struct ListNode{int value;ListNode *next;ListNode(int x){ value = x; }};//排序:小与x都在大于或等于x的前面ListNode *reorderXList(ListNode *head, int x){ListNode *newhead = NULL;ListNode *aDummy = new ListNode(0);ListNode *aCurr = aDummy;ListNode *bDummy = new ListNode(0);ListNode *bCurr = bDummy;while (head){ListNode *next = head->next;head->next = NULL;if (head->value < x){aCurr->next = head;aCurr = head;//后移}else{bCurr->next = head;bCurr = head;}head = next;}aCurr->next = bDummy->next;//连接起来newhead = aDummy->next;//新的头节点delete aDummy;delete bDummy;return newhead;}int main(){ListNode *a1, *a2, *a3, *a4;ListNode *head;head = (ListNode*)malloc(sizeof(ListNode));a1 = (ListNode*)malloc(sizeof(ListNode));a2 = (ListNode*)malloc(sizeof(ListNode));a3 = (ListNode*)malloc(sizeof(ListNode));a4 = (ListNode*)malloc(sizeof(ListNode));head->next = a1;a1->value = 5;a1->next = a2;a2->value = 8;a2->next = a3;a3->value = 3;a3->next = a4;a4->value = 6;a4->next = NULL;ListNode *resHead;resHead = reorderXList(head, 6);return 0;}


原创粉丝点击