在单向链表中如何快速查到倒数第n个节点 这简直是一种神奇的思路!!!!leetcode 删除倒数第n个节点

放肆的年华 提交于 2019-11-29 20:44:34

在单向链表中如何快速查到倒数第n个节点?

操作方法和步骤:

(1)定义2个指针p1,p2。

(2)使用循环让p2指向顺数第n个节点,同时p1指向第头结点;

(3)然后,p1和p2同时移动,直到p2指向NULL,此时p1应该指向倒数第n个节点。

19. Remove Nth Node From End of List

方法一:

<span style="font-family:SimHei;font-size:18px;">/**
 * 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) {
        int k=0;
		ListNode *p=head;
		while(p)
		{
			k++;
			p=p->next;
		}
		
		if(head==NULL || head->next==NULL)
			return NULL;
		else if(head->next->next==NULL)
		{
			if(n==1)
				head->next=NULL;
			if(n==2)
				head=head->next;
			return head; 
		}
		//有三个以上节点  要用到三个指针
		else
		{
			ListNode *pre=head;
			//ListNode *cur=pre->next;
			if((k-n+1)==1)
			{   pre = pre->next;
				return pre;
			}
			for(int i=2;i<=(k-n);i++)
			{
				pre=pre->next;
			}
			pre->next=pre->next->next;
			return head;
		}
        
    
    }
};</span>
方法二: 真的好神奇

class Solution{
public:
	ListNode* removeNthFromEnd(ListNode* head, int n){
		ListNode *cur=head;
		ListNode *pre=head;
		for(int i=0;i<n;i++)
		{
			cur=cur->next;
		}
		if(!cur)
		{
			head=head->next;
			return head;
		}
		while(cur->next)
		{
			pre=pre->next;
			cur=cur->next;
		}
		pre->next=pre->next->next;
		return head;
	}
};


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!