链表

/*
链表的基本操作
*/
#include<iostream>
using namespace std;
//定义节点的结构体
struct Node{
int val;
Node * next;

Node(int _val):val(_val),next(NULL){} //有参构造
};

int main(){
Node* p =new Node(1); //返回的地址,类似java 等价写法:Node node = Node(1); Node *p=&node;
Node* q =new Node(2); //auto,可以自动识别new Node返回值的类型
Node* o =new Node(3);

p->next=q; //p指向q
q->next=o; //q指向o

Node* head=p; //定义头节点,主要是用于记录

//添加一个节点(头插法)
Node* u =new Node(4);
u->next=head; //新加节点指向头节点
head=u; //更新头节点

//删除一个节点(链表的删除,不是说将这个节点干掉,而是在原链表遍历的时候,遍历不到即可!)
head->next=head->next->next;

//遍历链表
for(Node* i=head;i;i=i->next){
cout<<i->val<<endl;
}

return 0;

}

//两个链表的归并

class solution{
public:
while(l1&&l2)//遍历
if(l1->val<l2->val)
{
tail=tail->next=l1;
l1=l1->next;//指针更替
else
{
tail=tail->next=l2;
l2=l2->next;
}
}
if(l1) tail->next=l1;//尾节点
if(l2) tail->next=l2;

 

posted @ 2021-08-17 10:35  YUI唯  阅读(80)  评论(0)    收藏  举报