给定一个单向链表中的某个节点,请删除这个节点,但要求只能访问该节点。若该节点为尾节点,返回false,否则返回true
//先判断,再删除 class Remove { public: bool removeNode(ListNode* pNode) { if(pNode == NULL || (pNode != NULL && pNode->next == NULL )) return false; pNode->val = pNode->next->val; pNode->next = pNode->next->next; delete pNode->next; return true; } };
class Remove { public: bool removeNode(ListNode* pNode) { // write code here // 尾节点 if (pNode->next == NULL) { delete pNode; return false; } else { ListNode* nextNode; nextNode = pNode->next; pNode->val = nextNode->val; pNode->next = nextNode->next; delete nextNode; return true; } } };
class Remove { public: bool removeNode(ListNode* pNode) { ListNode* qNode = pNode->next; if (!qNode) { return false; } // swap pNode->val ^= qNode->val; qNode->val ^= pNode->val; pNode->val ^= qNode->val; // delete pNode->next = qNode->next; qNode->next = nullptr; delete qNode; return true; } };
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} };*/ class Remove { public: bool removeNode(ListNode* pNode) { if(!pNode->next) return false; return true; } };
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Remove { public boolean removeNode(ListNode pNode) { ListNode cur=pNode; if(cur.next==null) return false; else return true; } }
public class Remove { public boolean removeNode(ListNode pNode) { // write code here if (pNode == null) { return false; } if (pNode.next == null) { pNode = null; return false; } else { pNode = pNode.next; } return true; } }
# -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Remove: def removeNode(self, pNode): if not pNode or not pNode.next: return False pNode.val = pNode.next.val pNode.next = pNode.next.next return True
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Remove { public boolean removeNode(ListNode pNode) { if(pNode.next == null){ return false; }else{ pNode.val = pNode.next.val; pNode.next = pNode.next.next; return true; } } }
class Remove { public: bool removeNode(ListNode* pNode) { // write code here if(pNode->next==NULL){ return false; }else{ //由于是单向链表,所以访问不到前一个节点,只能获取pNode节点之后的所有节点 //为了实现删除效果,可以把后续节点的值都依次往前复制,最终删除最后一个节点 ListNode *cur=pNode,*post=cur->next; /* while(post){ if(post->next==NULL)break; cur->val=post->val; cur=post; post = post->next; } cur->next=NULL; */ if(post){ cur->val=post->val; cur->next=post->next; } delete post; return true; } } };