删除指定节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *leader=head;
ListNode *temp=head;
for (int i=0;i<n+1;i++)
{
leader=leader->next;
}
while(leader)
{
temp=temp->next;
leader=leader->next;
}
if(temp->next!=NULL)//Line 23: member access within null pointer of type 'struct ListNode'
{
temp->next=temp->next->next;
}
return head;
}
};
关于报错的原因是因为complier不能确定->next->next是不是等于null,代码还是选择参考链接的吧
链表反转
链表反转 这篇博文写的很好了
判断环形链表
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast=head;
ListNode* slow=head;
do{
for(int i=0;i<2;i++)
{
if(fast!=NULL)
fast=fast->next;
else
return false;
}
for(int i=0;i<1;i++)
{
slow=slow->next;
}
}while(fast!=slow);
return true;
}
};
虽然两个for循环可以用更高效的语句代替,但拓展性就不强了 whatever
判断回文
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next)
return true;
ListNode* middle=findmiddle(head);
if(middle)
middle->next=reverseList(middle->next);
else
return true;
ListNode* p=head;
ListNode* q=middle->next;
while(p!=NULL&&q!=NULL&&p->val==q->val)
{
p=p->next;
if(q->next)
q=q->next;
else
return true;
}
return false;
}
ListNode* findmiddle(ListNode* head){
ListNode* fast=head;
ListNode* slow=head;
while(fast&&fast->next)
{
fast=fast->next->next;
slow=slow->next;
}
return slow;
}
ListNode* reverseList(ListNode* head)
{
ListNode* newList=NULL;
ListNode* p=head;
while(p)
{
ListNode* temp=p->next;
p->next=newList;
newList=p;
p=temp;
}
return newList;
}
};
终端上调试都ok,就是不能通过。。。
合并两个有序链表
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode *head = new ListNode(0);//我这一天创建节点都是用的ListNode* head=NULLL 终于知道错哪了,好蠢!
ListNode *res = head;
while (l1&&l2) {
if (l1->val <= l2->val) {
res->next = l1;
l1 = l1->next;
}
else {
res->next = l2;
l2 = l2->next;
}
res = res->next;
}
if (l1) res->next = l1;
else res->next = l2;
return head->next;
}
过些时候把递归的方法写出来