Calculate the last node of the linked list
Using two pointers is similar to determining whether a linked list forms a ring.
Code:
#include
#include
using namespace std;typedef struct node {int data;struct node *next ;}Node,*pNode;void creatNode( pNode &pHead ){bool isFirst=true;pNode p,q;int temp;scanf("%d",&temp);while(temp){p=(pNode)malloc(sizeof(Node));p->data = temp;p->next = NULL;if(isFirst){q=pHead=p;isFirst = false;}else{q->next = p;q = p;}scanf("%d",&temp);}}void print(pNode p){while(p){cout<
data << " ";p = p->next;}}pNode printLast(pNode pHead,unsigned int m){if(NULL == pHead || m==0)return NULL ;pNode pAhead = pHead;pNode pBehind = pHead;for(int i=1;i<=m;i++){if(pAhead->next != NULL)pAhead = pAhead->next;elsereturn NULL;}while(pAhead){pAhead = pAhead->next;pBehind = pBehind->next;}return pBehind;}int main(){ pNode pHead=NULL;creatNode(pHead);print(pHead); cout<
data; return 0;}
Running result: