题目:在给定单链表的头结点指针和一个结点指针,定义一个函数在O(1)时间删除该结点。
代码:
1 #include <stdio.h> 2 #include "malloc.h" 3 struct ListNode 4 { 5 int value; 6 ListNode *next; 7 }; 8 //尾插法创建链表 9 ListNode *createList() 10 { 11 ListNode *H = (ListNode *)malloc(sizeof(ListNode)); 12 H->next = NULL; 13 ListNode *s, *r = H; //r指向尾节点,s为要插入的结点 14 int x; 15 scanf_s("%d",&x); 16 while (x!=-1) 17 { 18 s = (ListNode *)malloc(sizeof(ListNode)); 19 s->value = x; 20 s->next = r->next; 21 r->next = s; 22 r = s; 23 scanf_s("%d", &x); 24 } 25 return H; 26 } 27 void DeleteNode(ListNode **pListHead,ListNode *pToDelete) 28 { 29 if (pListHead == NULL || *pListHead == NULL || pToDelete == NULL) 30 return; 31 //要删除的结点不是尾结点,将需要删除的结点后面的结点覆盖到要删除的结点,将后面的结点删除 32 if (pToDelete->next != NULL) 33 { 34 ListNode *pNode = pToDelete->next; 35 pToDelete->value = pNode->value; 36 pToDelete->next = pNode->next; 37 delete pNode; 38 pNode = NULL; 39 } 40 //链表中只有一个结点,删除头结点(也是尾结点) 41 else if (*pListHead == pToDelete) 42 { 43 delete pToDelete; 44 pToDelete = NULL; 45 pListHead = NULL; 46 } 47 //链表中有多个结点,要删除的结点在尾部,需要找到删除结点的前一个结点(常规方法) 48 else 49 { 50 ListNode *pNodes = *pListHead; 51 while (pNodes->next != pToDelete) 52 { 53 pNodes = pNodes->next; 54 } 55 pNodes->next = NULL; 56 delete pToDelete; 57 pToDelete = NULL; 58 } 59 } 60 ListNode *find(ListNode *list, int x) 61 { 62 ListNode *fq; 63 fq = list->next; 64 if (fq == NULL) 65 return NULL; 66 while (fq != NULL) 67 { 68 if (fq->value == x) 69 return fq; 70 fq = fq->next; 71 } 72 return NULL; 73 } 74 75 int main() 76 { 77 int x; 78 ListNode *p,*q; 79 ListNode *H = (ListNode *)malloc(sizeof(ListNode)); 80 printf("输入单链表的结点值,以-1结束:"); 81 H = createList(); 82 printf("输入要删除的结点的值:"); 83 scanf_s("%d",&x); 84 q = find(H,x); 85 DeleteNode(&H,q); 86 p = H->next; 87 printf("删除一个结点%d后的值为 :",x); 88 while (p != NULL) 89 { 90 printf("%3d",p->value); 91 p = p->next; 92 } 93 printf("\n"); 94 95 return 0; 96 } 97 98 /* 99 输入单链表的结点值,以-1结束:1 2 3 4 5 6 -1 100 输入要删除的结点的值:1 101 删除一个结点1后的值为 : 2 3 4 5 6 102 请按任意键继续. . . 103 104 输入单链表的结点值,以-1结束:1 2 3 4 5 6 -1 105 输入要删除的结点的值:3 106 删除一个结点3后的值为 : 1 2 4 5 6 107 请按任意键继续. . . 108 109 输入单链表的结点值,以-1结束:1 2 3 4 5 6 -1 110 输入要删除的结点的值:6 111 删除一个结点6后的值为 : 1 2 3 4 5 112 请按任意键继续. . . 113 */
时间: 2024-10-04 09:23:24