zoukankan      html  css  js  c++  java
  • 删除链表的节点(Python and C++解法)

    题目:

    给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。

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

    示例 1:

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

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof

    思路:

      建立一个空节点作为哨兵节点,可以把首尾等特殊情况一般化,且方便返回结果,使用双指针将更加方便操作链表。

    Python解法:

     1 class ListNode:
     2     def __init__(self, x):
     3         self.val = x
     4         self.next = None
     5 
     6 
     7 class Solution:
     8     def deleteNode(self, head: ListNode, val: int) -> ListNode:
     9         tempHead = ListNode(None)  # 构建哨兵节点
    10         tempHead.next = head
    11 
    12         prePtr = tempHead  # 使用双指针
    13         postPtr = head
    14 
    15         while postPtr:
    16             if postPtr.val == val:
    17                 prePtr.next = postPtr.next
    18                 break
    19             prePtr = prePtr.next
    20             postPtr = postPtr.next
    21         return tempHead.next

    C++解法:

     1 struct ListNode {
     2      int val;
     3      ListNode *next;
     4      ListNode(int x) : val(x), next(NULL) {}
     5  };
     6  
     7 class Solution {
     8 public:
     9     ListNode* deleteNode(ListNode* head, int val) {
    10         ListNode *tempHead = new ListNode(-1); // 哨兵节点,创建节点一定要用new!!!!!!!!!!!!!!
    11         tempHead->next = head;
    12 
    13         ListNode *prePtr = tempHead;
    14         ListNode *postPtr = head;
    15 
    16         while (postPtr) {
    17             if (postPtr->val == val) {
    18                 prePtr->next = postPtr->next;  // 画图确定指针指向关系,按照箭头确定指向
    19                 break;
    20             }
    21             postPtr = postPtr->next;
    22             prePtr = prePtr->next;
    23         }
    24         return tempHead->next;
    25     }
    26 };
  • 相关阅读:
    常见HTTP状态码(200、301、302、500等)解说
    HTTP协议详解(真的很经典)
    计算机网络基础知识总结
    js调试中打印语句
    关于函数return的一些理解与小实例
    网站的导航菜单 远择一个栏目跳转后,为导航菜单的这个栏目增加选中的样式的思路
    alias记录
    利用vue-cli配合vue-router搭建一个完整的spa流程
    node+vue-cli+webpack搭建教程
    nodejs参考文章
  • 原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13221084.html
Copyright © 2011-2022 走看看