第10章 使用结构和指针

  1. 单链表

typedef struct NODE {

struct NODE *link;

int value;

} Node;

 

插入到一个有序单链表:

#include<stdio.h>

#include<stdlib.h>

#include "sll_node.h"

 

#define FALSE 0

#define TRUE 1

 

int sll_insert( Node **linkp, int new_value)  //指针的指针

{

Node *current;

Node *new;

 

//寻找正确的插入位置,方法是按序访问链表,直到到达一个

//其值大于或等于新值的节点

 

while((current= *linkp)!=NULL && current->value<new_value)

linkp=¤t->link;

 

new=(Node *)malloc(sizeof( Node ));

if( new == NULL )

return FALSE;

new->value = new_value;

 

//在链表中插入新节点,并返回TRUE

 

new->link = current;

*linkp = new;

return TRUE;

}

 

2.双链表

 

typedef struct NODE {

struct NODE *fwd;  //指向后一个节点

struct NODE *bwd;  //指向前一个节点

int value;

} Node ;

 

在双链表插入节点

#include<stdio.h>

#include<stdlib.h>

#include "doubly_liked_list_node.h"

 

int dll_insert( Node *rootp, int value)

{

Node *this;     //指向应该在新节点之前的那个节点

Node *next;     //指向应该在新节点之后的那个节点

Node *newnode;

 

for ( this = rootp; (next = this->fwd)!=NULL; this = next)

{

if ( next->value == value)

return 0;

if( next->value > value)

break;

}

newnode = (Node *)malloc(sizeof( Node));

if ( newnode == NULL )

return -1;

newnode->value = value;

 

//把新节点添加到链表中

 

newnode->fwd = next;

this->fwd=newnode;

 

if( this != rootp )

newnode->bwd = this;

else

newnode->bwd = NULL;

 

if( next != NULL )

next->bwd = newnode;

else

rootp->bwd = newnode;

return 1;

}

}

 

15章 输入/输出函数

1fseek()ftell()的用法

int  fseek( FILE  *stream, long  offset, int  from);

int  ftell( FILE  *stream);

  ftell 函数返回流的当前位置

  fseek 函数改变下一个读取写入操作的位置。第一个参数:一个指向被搜索文件的FILE指针。第二个参数:偏移量,表示从起始要移动的距离,可以为正(前移)、负(后移)、零(保持不动)。第三个参数:模式,用来标识起始点(SEEK_SET:文件开始; SEEK_CUR:当前位置; SEEK_END:文件结尾)

fseek( fp, l0L , SEEK_SET )  //找到文件的第10个字节

 

#include<stdio.h>

#include<stdlib.h>

 

#define CNTL_Z '\032'

#define SLEN 50

 

int main()

{

char file[SLEN];

char ch;

FILE *fp;

long count ,last;

 

puts("Enter the name of the file to be processed:");

gets(file);

if((fp = fopen(file,"rb"))==NULL)

{

printf("reverse can't open %s \n",file);

exit(1);

}

fseek(fp,0L,SEEK_END); //定位到文件结尾处

last=ftell(fp);

for(count=1L;count<=last;count++)

{

fseek(fp,-count,SEEK_END);

ch=getc(fp);

if(ch!=CNTL_Z && ch!='\r')

putchar(ch);

}

putchar('\n');

fclose(fp);

return 0;

 

}

运行结果:

 

posted on 2016-04-27 11:23  绽放的四叶草  阅读(343)  评论(0编辑  收藏  举报