1: 单链表中查找倒数第n个元素
通过一次遍历找到单链表中倒数第n个节点,链表可能相当大,可使用辅助空间,但是辅助空间的数目必须固定,不能和n有关。
单向链表的特点是遍历到末尾后不能反向重数N个节点。因此必须在到达尾部的同时找到倒数第N个节点。
不管是顺数n个还是倒数n个,其实都是距离-标尺问题。标尺是一段距离可以用线段的两个端点来衡量,我们能够判断倒数第一个节点,因为他的next==NULL。如果我们用两个指针,并保持他们的距离为n,那么当这个线段的右端指向末尾节点时,左端节点就指向倒数第n个节点。
01 iNode * GetLastNnode(iNode * head, int n)
02 {
03 iNode * pfirst=head;
04 iNode *psecond=head;
06 int counter;
07 //第1步:建立标尺,移动pfirst N步
08 for(counter=0; counter<n; counter++)
09 {
10 if(NULL == pfirst)
11 break; // 此时pfirst->next无意义
12 pfirst=pfirst->next;
13 }
15 if(n != counter) //长度不够n,未找到倒数第n个节点
16 return NULL;
18 //第2步:保持距离让标尺向右移动,直到右端指向末尾,左端即结果
19 while(pfirst!=NULL)
20 {
21 pfirst=pfirst->next;
22 psecond=psecond->next;
23 }
24 return psecond;
25 }
28 iNode * GetLastNnode ( iNode *head, int n)
29 {
30 iNode * pfirst = head;
31 iNode * psecond = NULL;//可能没有n个
32 while( n-- > 0 && (pfirst!= NULL)
33 {
34 pfirst = pfirst ->next;
35 }
37 if(pfirst!= NULL)// 有n个节点
38 psecond = head;
40 while(pfirst!=NULL)
41 {
42 pfirst = pfirst ->next;
43 psecond = psecond ->next;
44 }
45 return psecond; //只有一个出口,无论是否有n个节点,都能返回正确值
46 }
一次遍历单向链表找到中间节点
和上面的思路类似,设置2个指针,一个走2步时,另一个走1步。那么一个走到头时,另一个走到中间。
01 iNode * GetMiddleNode ( iNode *head )
02 {
03 iNode *p1 = head;
04 iNode *p2 = p1;
05 while( p2 )
06 {
07 p2 = p2->next;
08 if(p2)
09 {
10 p2 = p2->next;
11 p1=p1->next;
12 }
13 }
14 return p1;
15 }
2:找到单向链表中间的那个元素,如果有两个则取前面一个。
#include <iostream>
using namespace std;
typedef struct node
{
int value;
node* next;
}Lnode,*Pnode;
int find_mid(Lnode* head)
{
Lnode* pre,*curr;
curr = head;
pre = head;
int i = 1;
for (;curr != NULL; curr = curr->next)
{
if (i%2 == 0)
{
pre = pre->next;
}
i ++;
}
return pre->value;
}
//有头结点
int main()
{
Lnode* head = new Lnode;
head->next = NULL;
Lnode* nod = head;
int val;
cout << "输入数据(int类型,以0结束): ";
cin >> val;
while (val != 0)
{
Lnode* curr = new node;
curr->value = val;
curr->next = NULL;
nod->next = curr;
nod = nod->next;
cin >> val;
}
cout << "链表数据为:";
for (Lnode* pre = head->next;pre!=NULL;pre=pre->next)
{
cout << pre->value <<" ";
}
cout << endl;
cout << "中间的数是:" << find_mid(head) << endl;
return 0;
}