为了保证对整个链表的操作都是统一的,所以,在链表head节点前,增加一个dummy节点。
//方式一
ListNode* dummy = new ListNode(0, head); //增加dummy节点
//方式二
ListNode* dummy=new ListNode();
dummy->next=head;
附上力扣19题,删除链表的倒数第N个结点:
class Solution {
public:
int getLength(ListNode* head) {
int length = 0;
while (head) {
++length;
head = head->next;
}
return length;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
// ListNode* dummy = new ListNode(0, head); //增加dummy节点
ListNode* dummy=new ListNode();
dummy->next=head;
int length = getLength(head); //计算链表长度
ListNode* cur = dummy;
for (int i = 1; i < length - n + 1; ++i) { //遍历结束时,cur已经指向了第size-n+1个结点
cur = cur->next;
}
cur->next = cur->next->next;
ListNode* ans = dummy->next;
// delete dummy;
return ans;
}
};