链表笔记(自用)
作者:互联网
链表定义(来源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;
}
删除链表倒数第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;
}
标签:head,ListNode,val,int,笔记,next,链表,自用 来源: https://blog.csdn.net/M3_0352/article/details/123621558