题目:输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第一个节点。
c++实现:
#include<iostream>
#include<stack>
using namespace std;
struct ListNode
{
int m_nkey;
ListNode* m_pNext;
};
//建立一个链表用头插法
void AddToHead(ListNode** pHead,int value)
{
ListNode* pNew = new ListNode();
pNew->m_nkey = value;
pNew->m_pNext = NULL;
if(*pHead == NULL)
{
*pHead = pNew;
}
else
{
// ListNode *pNode = *pHead;
// pNew->m_pNext = pNode;
// pNode->m_pNext = pNew;
// *pHead = pNode;
pNew->m_pNext = *pHead;
*pHead = pNew;
}
} //删除列表中的节点
//删除链表中重复的节点
//找到倒数第k个节点
ListNode* Find(ListNode *pHead,unsigned int k)
{
if(pHead==NULL || k==0)
return NULL;
ListNode* pFirst = pHead;
ListNode* pBehind;
for(int i=0; i<k-1;i++)
{
if(pFirst->m_pNext != NULL)
{
pFirst = pFirst->m_pNext;
}
else{
return NULL;
}
}
pBehind = pHead;
while(pFirst->m_pNext != NULL)
{
pFirst = pFirst->m_pNext;
pBehind = pBehind->m_pNext;
}
return pBehind;
}
void print(ListNode * pHead)
{
ListNode* pNode = pHead;
while(pNode!=NULL)
{
cout<<pNode->m_nkey<<" ";
pNode = pNode->m_pNext;
}
}
int main()
{
int num = 10;
ListNode *p = new ListNode();
p = NULL;
ListNode **pHead = &p;
AddToHead(pHead,1);
AddToHead(pHead,2);
AddToHead(pHead,3);
AddToHead(pHead,4);
AddToHead(pHead,5);
AddToHead(pHead,6);
AddToHead(pHead,7);
//DeleteDuplication(pHead);
ListNode *res = Find(*pHead, 4);
cout<<res->m_nkey;
// ListNode *del = new ListNode();
// print(*pHead);
}
JAVA实现:
package jianzhi_offer;
public class DeleteDuplication {
public static class ListNode{
private int data;
private ListNode next;
public ListNode(int data,ListNode next)
{
this.data = data;
this.next = next;
}
}
public static ListNode Find(ListNode head, int k)
{
if(head == null || k==0)
{
return null;
}
ListNode firstNode;
ListNode behind;
firstNode = head;
for(int i=0; i<k-1; i++)
{
if(firstNode.next!=null)
{
firstNode = firstNode.next;
}
else {
return null;
}
}
behind = head;
while(firstNode.next!=null)
{
firstNode = firstNode.next;
behind = behind.next;
}
return behind;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode tail = new ListNode(7,null);
ListNode c = new ListNode(6,tail);
ListNode b = new ListNode(5,c);
ListNode a = new ListNode(4,b);
ListNode e = new ListNode(3,a);
ListNode d = new ListNode(2,e);
ListNode head = new ListNode(1,d);
ListNode res = Find(head,2);
if(res!=null)
System.out.println(res.data+" ");
while(head!=null)
{
System.out.println(head.data + " ");
head = head.next;
}
}
}