网络编程
位置:首页>> 网络编程>> Python编程>> 基于Python和C++实现删除链表的节点

基于Python和C++实现删除链表的节点

作者:孔子?孟子?小柱子!  发布时间:2022-11-19 13:52:11 

标签:Python,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.

思路:

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

Python解法:


class ListNode:
 def __init__(self, x):
   self.val = x
   self.next = None

class Solution:
 def deleteNode(self, head: ListNode, val: int) -> ListNode:
   tempHead = ListNode(None) # 构建哨兵节点
   tempHead.next = head

prePtr = tempHead # 使用双指针
   postPtr = head

while postPtr:
     if postPtr.val == val:
       prePtr.next = postPtr.next
       break
     prePtr = prePtr.next
     postPtr = postPtr.next
   return tempHead.next

C++解法:


struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
 ListNode* deleteNode(ListNode* head, int val) {
   ListNode *tempHead = new ListNode(-1); // 哨兵节点,创建节点一定要用new!!!!!!!!!!!!!!
   tempHead->next = head;

ListNode *prePtr = tempHead;
   ListNode *postPtr = head;

while (postPtr) {
     if (postPtr->val == val) {
       prePtr->next = postPtr->next; // 画图确定指针指向关系,按照箭头确定指向
       break;
     }
     postPtr = postPtr->next;
     prePtr = prePtr->next;
   }
   return tempHead->next;
 }
};

来源:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13221084.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com