单链表:
双链表:
循环链表:(可用于解决约瑟夫环问题)
*****************************************
链表定义:
ListNode struct{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){};
/******相当于
ListNode(int x)
{
val=x;
next=nullptr;
}
*********/
};
//自己定义构造函数初始化节点:
ListNode* head = new ListNode(5);
//使用默认构造函数初始化节点:
ListNode* head = new ListNode();
head->val = 5;
链表的特性和数组的特性对比:
参考:代码思想录:链表
*****************************************
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyhead = new ListNode(0); // 设置一个虚拟头结点
dummyhead->next = head; // 将虚拟头结点指向head,这样方便后面做删除操作
ListNode* cur = dummyhead;
while (cur->next != NULL){
if(cur->next->val==val){
ListNode* temp=cur->next;//定义temp存放cur->next的地址,防止丢失
cur->next=cur->next->next;
delete temp;
}
else
cur=cur->next;
}
head=dummyhead->next;
delete dummyhead;
return head;//会返回整个链表,包括头节点以及头节点后面的所有节点。
}
};
*****************************************
ListNode* pre=NULL;
ListNode* cur=head;
temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre=NULL;
ListNode* cur=head;
ListNode* temp=new ListNode();
while(cur!=NULL){//cur指针最后指向空时,pre指针刚好指向链尾
temp=cur->next;//存放cur->next的地址,防止丢失
cur->next=pre;
//反转完成
pre=cur;
cur=temp;
}
return pre;//此时pre即为头节点
}
};
*****************************************
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyhead=new ListNode();
dummyhead->next=head;
ListNode* cur=dummyhead;
ListNode* temp1;
ListNode* temp2;
while(cur->next != NULL && cur->next->next != NULL){
/*如果使用while( cur->next->next != NULL){}时,如果cur->next是NULL,那么尝试访问
cur->next->next会导致空指针异常。因此,需要在条件中添加额外的检查cur->next != NULL*/
temp1=cur->next;//temp1存放节点1的地址
temp2=cur->next->next->next;//temp2存放节点3的地址
cur->next=cur->next->next;//将虚拟头节点指向节点2
cur->next->next=temp1;//将节点2指向节点1
cur->next->next->next=temp2;//将节点1指向节点3
cur=cur->next->next;//将cur指针移动到交换后的节点1
}
head=dummyhead->next;
delete dummyhead;
return head;
}
};