分享:简单的链表操作
链表的所有操作,无论插入,还是删除节点,还是逆序,都是对next值的修改!!!!!!!!!再此,根指针是一个特例,原因在于,函数无法访问根指针,因此这里需要二级指针。
当然,解决函数无法访问根指针有多个办法,第一,传递一个完整的节点。第二,全局变量。第三,二级指针。
这样一看,二级指针可谓最优化选择。
至于双链表,我还有一个最后的查找没有完成。悲剧。因为双链表,可以从多个方向进行遍历,所以一直没有完成。
程序代码://调用示例:
#include <stdio.h>
#include "List.h"
int
main( void )
{
Node *Root;
Node *P;
int value;
Root = NULL;
while( 1 == scanf( "%d", &value ) )//插入测试,升序。如要按照输入顺序插入,那么需要删除InsertNode while循环中的值判断
InsertList( &Root, value );
PrintList( Root, ' ' );//打印测试。该函数接受一个节点指针和一个字符,用来作为打印的分割符。
printf( "\n" );
getchar();
while( 1 == scanf( "%d", &value ) )
DeleteNode( &Root, value );//删除节点,接受一个节点指针和一个值,注意,你需要传递该指针本身的地址。
PrintList( Root, ' ' );
printf( "\n" );
Root = ReverseList( Root );//逆序。返回新链表的指针。这里可以也可以用二级指针来做到没有返回值,但是不够灵活。
PrintList( Root, ' ' );
printf( "\n" );
getchar();
while( 1 == scanf( "%d", &value ) )
{
P = FindNode( Root, value );
printf("%d",P->Value);
}
DeleteList( &Root );//删除链表。
return 0;
}
程序代码:#ifndef List_H
#define List_H
typedef struct NODE {
int Value;
struct NODE *Next;
}Node;
void
PrintList( Node *RootP,char Spacech );
int
InsertList( Node **RootP, int value );
void
DeleteList( Node **RootP );
void
DeleteNode( Node **RootP, int value );
Node *
FindNode( Node *Root, int value );
Node *
ReverseList( Node *first );
#endif
程序代码:#include <stdio.h>
#include <stdlib.h>
#include "List.h"
int
InsertList( Node **RootP, int value )
{
Node *NewCell;
Node *Current;
while( NULL != ( Current = *RootP ) && value > Current->Value )
RootP = &Current->Next;//Current往前遍历,用RootP来保存之前的Next值,这样,当Current找到插入点的时候,RootP就可以告诉我们,那个Next需要修改
//至于链表为空,还是插入点为头部,尾部,这些无需考虑,因为newcell->next一定是指向current,
NewCell = (Node *)malloc( sizeof(Node) );
if( NULL == NewCell )
return 0;
NewCell->Value = value;
NewCell->Next = Current;
*RootP = NewCell;
return 1;
}
void
DeleteNode( Node **RootP , int value )
{
Node *Current;
while( NULL != ( Current = *RootP ) && value != Current->Value )
RootP = &Current->Next;//如上
if( NULL == Current )
return;
*RootP = Current->Next;
free( Current );
}
void
PrintList( Node *RootP, char Spacech )
{
Node *Current;
while( NULL != ( Current = RootP ) )
{
printf("%d%c",Current->Value,Spacech);
RootP = Current->Next;
}
}
void
DeleteList( Node **RootP )
{
Node *Current;
Node *Temp;
Current = *RootP;
*RootP = NULL;//根指针设置为NULL
while( NULL != Current )
{
Temp = Current->Next;//Temp保存下一节点
free( Current );//释放当前节点
Current = Temp;//更新Current的值
}
}
Node *
FindNode( Node *Root, int value )
{
Node *Next;
while( NULL != ( Next = Root ) && Next->Value != value )
Root = Next->Next;
return Next;
}
Node *
ReverseList( Node *first )
{
Node *current;
Node *next;
for( current = NULL; NULL != first; first = next )
{//first往前遍历,next保存下一节点。这样,first的值就是需要修改的值。
next = first->Next;
first->Next = current;
current = first;
}
return current;
}
[此贴子已经被作者于2017-3-21 20:38编辑过]








