链表定义(来源leetcode)
/**
* 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) {}
* };
*/
获取链表长度
int getLength(ListNode* head){
int count=0;
while(head){
count++;
head=head->next;
}
return count;
}
删除链表重复元素
ListNode* deleteDuplicates(ListNode* head) {
ListNode *cur=head;
while(cur&&cur->next){
if(cur->val==cur->next->val){
//ListNode *del=cur->next;
cur->next=cur->next->next;
//delete del;
}else
cur=cur->next;
}
return head;
}
删除链表倒数第n个元素
ListNode* removeNthFromEnd(ListNode* head, int n) {
//虚拟节点,避免头节点为空的现象;
ListNode* dummy=new ListNode(0,head); //the first member val to 0, and the second member next to head
int length=getLength(head);
ListNode* curr=dummy;
for(int i=1;i<length-n+1;i++){ //最终将curr定位在待删除元素前一个位置
curr=curr->next;
}
curr->next=curr->next->next;
ListNode *ans=dummy->next;
delete dummy;
return ans;
}
返回链表的中间节点,如果有两个,返回后一个
ListNode* middleNode(ListNode* head) {
//快慢指针
ListNode* fast=head;
ListNode* slow=head;
while(fast && fast->next){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
反转链表
ListNode* reverseLinkList(ListNode* head){
ListNode* curr=head;
ListNode* pre=nullptr;
while(curr){
ListNode* nextTemp=curr->next;
curr->next=pre;
pre=curr;
curr=nextTemp;
}
return pre;
}
寻找链表中间节点(数组法)
ListNode* middleNode(ListNode* head) {
//数组
vector<ListNode*> LinkList={head};
while(LinkList.back()->next)
LinkList.push_back(LinkList.back()->next);
return LinkList[LinkList.size()/2];
}