删除链表中指定位置的元素

来源:互联网 发布:麒麟linux 编辑:程序博客网 时间:2024/05/16 16:08

#include<stdio.h>
#include<iostream>
using namespace std;
typedef int Elemtype;
typedef struct node {
    Elemtype data;
    struct node* next;
};
node* Greatlist(int n)                       //创建链表
{
    node*p, *r, *head = NULL;
    r = (node*)malloc(sizeof(node));
    int i;
    Elemtype c;
    for (i = 1; i <= n; i++)
    {
        cin >> c;
        p = (node*)malloc(sizeof(node));
        p->data = c;
        p->next = NULL;
        if (head == NULL)
        {
            r=head= p;
        }
        else
        {
            
            r->next = p;
            r = p;
        }
    }
    return head;
}

int Linklen(node*head)                        //返回链表长度,本题中用不到这个函数
{
    int count = 0;
    node* p = head;
    while (p!=NULL)
    {
        count++;
        p=p->next;
    }
    return count;
}

node* getPtr(node* head, int pos)              //得到指定位置的链表元素的指针
{
    node* p = head;
    int i;
    for (i = 1; i < pos; i++)
    {
        p = p->next;
    }
    return p;
}

int main()
{
    node*l;
    cout << "input 10 interger:" << endl;
    l = Greatlist(10);
    cout << "the length is:" << Linklen(l) << endl;
    node*p, *q;
    p = getPtr(l, 4);
    q = p->next;
    p->next = q->next;
    free(q);
    cout << "the linklist after deleting the fifth node :" << endl;
    p = l;
    while (p)
    {
        cout << p->data << " ";
        p = p->next;
    }
    return 0;
}



0 0