本题要求实现一个函数,可查找单链表(无监督元)中某个元素的前驱结点。例如链表中的元素为1,6,3,2,4,查找3的前驱为6。如果表中无此元素或没有前驱则返回空指针。
函数接口定义:
ptr pre (ptr h,int x);
其中 h 和x是用户传入的参数,x为查找的元素。返回查找元素结点的地址。
pre结构定义:
typedef struct node//结构体定义{ 
int data;//存储数据 
struct node *next;//指向下一个结点的指针 
}snode,*ptr;//定义别名
裁判测试程序样例:
#include <stdio.h> 
typedef struct node//结构体定义 { 
int data; struct node *next; 
}snode,*ptr; 
ptr pre (ptr h,int x); 
int main() { 
ptr head,p; 
int x; head=creat();//构造链表,无需用户完成,细节不表 
scanf("%d",&x); 
p=pre(head,x); 
if(p==NULL) 
printf("None"); 
else printf("%d",p->data); 
return 0; } /* 请在这里填写答案 */
输入样例:
5
1 6 3 2 4
3
输出样例:
6代码实现:
ptr pre(ptrh,int x)
{
ptr p=h,q;
q=h->next;
while(q!=NULL){
if(q->data==x)return p;
p=p->next;
q=q->next;}
if(x==h->data)
return NULL;}