2.3-删除链表中间节点

来源:互联网 发布:农村人口老龄化数据 编辑:程序博客网 时间:2024/06/07 20:15

Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
EXAMPLE
Input: the node ‘c’ from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a->b->d->e

1.一开始就是认为自己找到mid node然后删除,用快慢指针就行。

2.然后看了下书的答案,他的意思是mid node作为参数传入,已经指定好了。

这样的话,我们不知道上个节点是啥,所以将next节点的数据与mid node交换,然后删除next节点。

#include <iostream>using namespace std;struct ListNode{    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};void show(ListNode *head){    while(head)    {        cout<<head->val;        head = head->next;    }    cout<<endl;}ListNode *createLinkedlist(int array[], int len){    ListNode *cur = new ListNode(0);    ListNode *head=cur;    for(int i=0; i<len; i++)    {        ListNode *p = new ListNode(array[i]);        cur->next=p;        cur=cur->next;    }    cur->next=NULL;    return head->next;}void deleteMid(ListNode *head){    ListNode *fast=head, *slow=head, *pre_slow=head;    while(fast->next!=NULL && fast->next->next!=NULL)    {        fast = fast->next->next;        pre_slow = slow;        slow = slow->next;    }    pre_slow->next = slow->next;}int delete_node(ListNode* midnode)//mid node 给你指定好了{    int data;    ListNode *p=node->next;    node->data=p->data;    node->next=p->next;    free(p);}int main(){    int a[] = {1,2,3,4,5,6,7,8,9};    ListNode *head = createLinkedlist(a,9);    deleteMid(head);    show(head);    int b[] = {1,2,3,4};    ListNode *head2 = createLinkedlist(b,4);    deleteMid(head2);    show(head2);    return 0;}


0 0