您的位置:首页 > 其它

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

2016-04-16 15:30 381 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: