Remove Nth Node From End of List

题目:

Given a linked list, remove the nth node from the end of list and return its head.

For example,

 Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.


思路1:

先将链表逆转,然后删除相应位的元素,再次逆转,输出链表

思路2:

设定两个指针,二者相差n-1,当后面的一个指针为空时,前一个指针即为所要删除的节点


代码:

#include <iostream>

using namespace std;

/**
 * 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) { //思路1
        /*将链表逆转*/
		if(head==NULL) return head;//head为空直接返回
		if(head->next==NULL && n==1) //链表只包含一个元素,直接删除
		{
			head=NULL;
			return head;
		}
		ListNode *q; //用于记录头结点
		ListNode *nex;//下一个节点
		ListNode *pre=NULL;//前一个节点
		ListNode *cur=head;//当前节点
		while(cur!=NULL)
		{
			nex=cur->next;
			cur->next=pre;
			pre=cur;
			cur=nex;			
		}
		head=pre;

       /*删除特定位置上的值*/
		q=head;
		if(n==1)
		{
			head=head->next;
		}
		else
		{
			while(--n)
		    {
			    pre=q;
			    q=q->next;
		     }
		     pre->next=q->next;
		}
		


		/*再次将链表逆转*/
	    pre=NULL;
		cur=head;
		while(cur!=NULL)
		{
			nex=cur->next;
			cur->next=pre;
			pre=cur;
			cur=nex;
		}
		head=pre;


		return head;
    }

	ListNode* removeNthFromEnd2(ListNode* head, int n) //思路2
	{
		if(head==NULL) return head;
		
		ListNode *first,*last,*pre=NULL;
		first=last=head;
		n--;
		while(n--&&last!=NULL)
		{
			last=last->next;
		}

		while(last->next!=NULL)
		{
			pre=first;
			first=first->next;
			last=last->next;
		}
		if(pre ==NULL)
		{
			head=first->next;
			delete first;
		}
		else
		{
			pre->next=first->next;
			delete first;
		}
		
		return head;
	}
};

int main()
{
	ListNode *head=new ListNode(1);
	ListNode *p;
	p=head;
/*
	p->next=new ListNode(2);
    p=p->next;
	
	p->next=new ListNode(3);
	p=p->next;

	p->next=new ListNode(4);
	p=p->next;

	p->next=new ListNode(5);
    p=p->next;
*/
	Solution s;
	head=NULL;
	head=s.removeNthFromEnd2(head,1);

	while(head!=NULL)
	{
		cout<<head->val<<"->";
		head=head->next;
	}

	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值