链表
http://www.cnblogs.com/lixiaohui-ambition/archive/2012/09/25/2703195.html
#include<iostream> #include<cstdio> #include<map> using namespace std; struct node { int val; node *next; }; //建立链表 node *Build(int n) { node *root=NULL; for(int i=1;i<=n;i++) { node *tmp=new node; tmp->val=i; tmp->next=root; root=tmp; } return root; } //打印出链表 void OutputList(node *root) { while(root!=NULL) { printf("%d ",root->val); root=root->next; } puts(""); } //链表反转 node *ReverseList(node *root) { if(root==NULL)return NULL; node *head=NULL; while(root!=NULL) { node *tmp=root;//摘下节点 root=root->next; tmp->next=head;//挂在尾部 head=tmp; } return head; } //查找倒数第k个节点,快指针到第k个节点后,快慢指针一起移动 node *GetKthNode(node *root,int k) { if(k==0||root==NULL)return NULL; node *first=root; node *second=root; while(--k&&first!=NULL) { first=first->next; } if(first==NULL)return NULL; while(first->next!=NULL) { first=first->next; second=second->next; } return second; } //已知两个单链表pHead1 和pHead2 各自有序,把它们合并成一个链表依然有序 //判断一个单链表中是否有环 //判断两个单链表是否相交,返回交点 int main() { int n; while(~scanf("%d",&n)) { node *root=new node; root=Build(n); root=ReverseList(root); OutputList(root); node *Kth=new node; Kth=GetKthNode(root,2); if(Kth)printf("%d\n",Kth->val); } return 0; }
浙公网安备 33010602011771号