目录
JZ52 两个链表的第一个公共结点
思路:让两个链表相加,则到达公共结点的距离相同;
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1 == NULL || pHead2 == NULL) return NULL;
ListNode* a = pHead1;
ListNode* b = pHead2;
while(a != b){
a = (a == NULL) ? pHead2 : a->next;
b = (b == NULL) ? pHead1 : b->next;
// cout<<a->val<<","<< b->val<<endl;
}
return a;
}
};
链表中倒数最后k个结点
使用双指针法;
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* FindKthToTail(ListNode* pHead, int k) {
// write code here
if(pHead == NULL) return NULL;
ListNode* l = pHead;
ListNode* r = pHead;
for(int i=0;i<k;i++) r= r->next;
while(r!= NULL)
{
l=l->next;
r=r->next;
}
return l;
}
};
删除链表中重复的结点:
增加一个头节点,方便我们删掉原来的头节点;
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead) {
//增加一个哨点,可以测试头节点和返回头节点;
ListNode* res = new ListNode(0);
res->next = pHead;
ListNode* pre = res;
ListNode* cur = pHead;
while(cur != NULL && cur->next !=NULL)
{
if(cur->val == cur->next->val)
{
int temp = cur->val;
while(cur->val == temp && cur != NULL)
{
cur = cur->next;
}
pre->next = cur;
}else{
pre = cur;
cur = cur->next;
cout<<pre->val<<",";
}
}
return res->next;
}
};