链表高效删除

来源:互联网 发布:淘宝店铺只有pc端装修 编辑:程序博客网 时间:2024/06/04 18:37

题目描述

实现一个算法,删除单向链表中间的某个结点,假定你只能访问该结点。

给定带删除的节点,请执行删除操作,若该节点为尾节点,返回false,否则返回true

#include "stdafx.h"#include <iostream> #include "string.h"#include <vector>using namespace std;struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};//ListNode *create(int value)//{//ListNode *p=new ListNode(2);//p->val=value;//p->next=NULL;//return p;//}ListNode* connection(ListNode *pNode1,ListNode *pNode2){while(pNode1->next!=NULL){pNode1=pNode1->next;}pNode1->next=pNode2;pNode2->next=NULL;return pNode1;}void print(ListNode* phead){while(phead){cout<<phead->val<<" ";phead=phead->next;}cout<<endl;}class Remove {public:    bool removeNode(ListNode* pNode){        // write code here        if (pNode->next==NULL)        {return false;        }else {//ListNode *qNode=pNode->next;pNode->val=pNode->next->val;pNode->next=pNode->next->next;//delete pNode->next;return true;}    }};int main(){//ListNode* pNode1=ListNode(1);//ListNode* pNode2=ListNode(2);ListNode pNode1(1);ListNode pNode2(2);ListNode pNode3(3);ListNode pNode4(4);connection(&pNode1,&pNode2);connection(&pNode1,&pNode3);connection(&pNode1,&pNode4);print(&pNode1);Remove pNode;int k;k=pNode.removeNode(&pNode2);print(&pNode1);}


0 0
原创粉丝点击