鱼C论坛

 找回密码
 立即注册
查看: 2294|回复: 0

[技术交流] C++刷剑指offer(面试题18. 删除链表的节点)【链表】

[复制链接]
发表于 2020-3-28 21:05:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 糖逗 于 2020-5-8 18:02 编辑

题目描述:
  1. 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

  2. 返回删除后的链表的头节点。

  3. 注意:此题对比原题有改动

  4. 示例 1:

  5. 输入: head = [4,5,1,9], val = 5
  6. 输出: [4,1,9]
  7. 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
  8. 示例 2:

  9. 输入: head = [4,5,1,9], val = 1
  10. 输出: [4,5,9]
  11. 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
  12.  

  13. 说明:

  14. 题目保证链表中节点的值互不相同
  15. 若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点

  16. 来源:力扣(LeetCode)
  17. 链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
  18. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. #include <iostream>

  2. using namespace std;

  3. struct ListNode{
  4.         int value;
  5.         ListNode* next;
  6.         ListNode(int x): value(x), next(NULL){
  7.         }
  8.        
  9. };


  10. void printList(ListNode* head){
  11.         ListNode* temp = head;
  12.         while(temp -> next != NULL){
  13.                 temp = temp -> next;
  14.                 cout << temp -> value << " ";
  15.         }
  16.         cout << endl;
  17.         cout << "---------" << endl;
  18.        
  19. }

  20. ListNode* deleteNode(ListNode* head, int val){
  21.         ListNode* temp = head;
  22.         ListNode* temp1 = head;
  23.         while(temp -> next != NULL){
  24.                 temp  = temp -> next;
  25.                 if(temp -> value == val){
  26.                         temp1 -> next = temp -> next;
  27.                 }
  28.                 else{
  29.                         temp1 = temp;
  30.                 }
  31.         }
  32.         return head;
  33. }

  34. int main(void){
  35.         ListNode* head = new ListNode(0);
  36.         ListNode* temp = head;
  37.         int number;
  38.         cout << "please send numbers that you want they to be included in singleList" << endl;
  39.         while(cin >> number){
  40.                 ListNode* node = new ListNode(number);
  41.                 temp -> next = node;
  42.                 temp = node;
  43.         }
  44.         cin.clear();
  45.         printList(head);
  46.        
  47.         int val;
  48.         cout << "please send a number that you want to delete:" << endl;
  49.         cin >> val;
  50.         ListNode* result = deleteNode(head, val);
  51.         printList(result);
  52.         return 0;
  53. }
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-13 03:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表