考虑特殊情况:
1. 链表头指针为空,n小于等于0是错误输入
1. 链表头指针为空,n小于等于0是错误输入
2. 链表实际节点数小于n
因此代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int a;
struct node *link;
}mynode;
int creat_tail(mynode *head,int n){
mynode *node = head,*new;
int x;
if(n <= 0){
printf("error: n <= 0");
return 0;
}
for(;n > 0;n--){
new = (mynode*)malloc(sizeof(mynode));
printf("enter a number:\n");
scanf("%d",&x);
new->a = x;
new->link = NULL;
node->link = new; //随动指针
node = node->link;
}
}
mynode* search(mynode *head,int n)
{
mynode *front = head,*behind = head;
if(head == NULL || n <= 0) return NULL;
while(front->link != NULL && n > 0){
front = front->link;
n--;
}
if(n > 0) return NULL;
while(front != NULL){
front = front->link;
behind = behind->link;
}
return behind;
}
//正向打印
void print_nodes1(mynode *head){
int n = 1;
mynode *node;
if(head != NULL){
node = head->link;
while(node != NULL){
printf("num:%d\t a=%d\n",n,node->a);
node = node->link;
n++;
}
}
}
void main()
{
mynode *head,*value;
creat_tail(head,1);
print_nodes1(head);
value = search(head,1);
printf("%d\n",value->a);
getch();
}