剑指 Offer 18. 删除链表的节点
题目描述:剑指 Offer 18. 删除链表的节点
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
ListNode * nHead = new ListNode();
nHead->next = head;
ListNode * cur = nHead;
while(cur->next){
if(cur->next->val == val){
cur->next = cur->next->next;
break;
}else{
cur = cur->next;
}
}
return nHead->next;
}
};
剑指 Offer 22. 链表中倒数第k个节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getKthFromEnd(ListNode* head, int k) {
ListNode * nHead = new ListNode();
nHead->next = head;
ListNode * cur = nHead;
ListNode * cur2 = nHead;
while(k--){
cur = cur->next;
}
while(cur){
cur2 = cur2->next;
cur = cur->next;
}
return cur2;
}
};