加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

链表的基本操作(C++)

发布时间:2020-12-15 04:51:09 所属栏目:百科 来源:网络整理
导读:#include "stdafx.h" #include #include using namespace std; template struct Node { T data; Node *next; }; template Node *CreatList(vector arr) { //Node *head = (Node *)malloc(sizeof(Node )); Node *head = new Node ; Node *pre = head; Node *p

#include "stdafx.h"

#include

#include

using namespace std;

template

struct Node {

T data;

Node *next;

};

template

Node *CreatList(vector &arr)

{

//Node *head = (Node*)malloc(sizeof(Node));

Node *head = new Node;

Node *pre = head;

Node *p = NULL;

for (unsigned int i = 0; i < arr.size(); i++)

{

//p= (Node*)malloc(sizeof(Node));

p = new Node;

pre->next = p;

p->data = arr[i];

pre = p;

}

p->next = NULL;

return head->next;

}

template

void PrintList(Node *head)

{

Node *p = new Node;

p->next = head; //为了方便遍历

while (p->next != NULL)

{

p = p->next;

cout << p->data << "->";

}

cout<<"NULL"<< endl;

}

template

Node* reverseList(Node *head)

{

Node *pre = NULL,*cur = head,*temp;

while (cur != NULL)

{

temp = cur->next;

cur->next = pre;//翻转

pre = cur;

cur = temp;

}

return pre;

}

//插入第n个元素后面

template

Node * addNode(Node *head,T val,int n)

{

Node *p = head;

int i = n - 1;

while (i > 0)

{

p = p->next;

i--;

}

Node *q = new Node;//要插入的元素

q->data = val;

q->next = p->next;

p->next = q;

return head;

}

//删除第n个元素后面

template

Node * delNode(Node *head,int n)

{

Node *p = head;

int i = n - 1;

while (i > 0)

{

p = p->next;

if (p->next == NULL)//最后一个元素,不作删除

return head;

i--;

}

if (p->next->next == NULL)//倒数第二个(删除最后一个)

p->next = NULL;

else

p->next = p->next->next;

return head;

}

int main()

{

vector arr(5);

arr = {1,2,3,4,5};

Node *head = CreatList(arr);

PrintList(head);

/*Node *rhead = reverseList(head);

PrintList(rhead);*/

Node *addhead = addNode(head,8,3);

PrintList(addhead);

delNode(addhead,5);

PrintList(addhead);

getchar();

return 0;

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读