永发信息网

线性表的单链表实现

答案:2  悬赏:80  手机版
解决时间 2021-02-02 03:51
  • 提问者网友:了了无期
  • 2021-02-01 15:06
线性表的单链表实现
1. 问题描述
线性表基本操作在单链表上的实现,包括:
(1)创建单链表;
(2)在单链表上查找第i个数据结点,返回其data值;
(3)在单链表第i个位置上插入一个取值为value的新的数据结点;
(4)删除单链表第i个数据结点,并返回该数据结点的取值;
(5)求单链表的长度。
2. 基本要求
用自己熟悉的编程语言(C或C++)实现即可。建议用C++通过设计链表模板来实现。
3. 测试数据
(1)线性表中数据元素的取值集合为{1,2,3,4,5,6,7,8};或线性表中数据元素的取值集合为{1.0,3.0,5.0,6.0,7.0,8.0},
最佳答案
  • 五星知识达人网友:平生事
  • 2021-02-01 15:17
Node *Locate(Node L,int x)
{
Node *p;
p = L.next;
while(p != NULL)
{
if (p->data == x)
{
return p; //找到返回结点的地址
}
p = p->next;
}
return NULL; //未找到
}
全部回答
  • 1楼网友:舍身薄凉客
  • 2021-02-01 16:28
第一个,我把以前写过的代码搬了过来,用的是数组,关键字就是元素本身的大小: #include <stdio.h> int* binary_search( int* beg, int* end, int val ) { int* mid; while( beg < end ) { mid = beg + ( (end - beg) >> 1 ); if( *mid == val ) return mid; else if( *mid < val ) beg = mid + 1; else end = mid; } return beg; } int main() { int a[] = { 1,1,2,3,5,5,6,7,8,9,-1 }; int b, *p, *q; for( p = a; *p != -1; ++p ) printf( "%d ", *p ); putchar( '\n' ); scanf( "%d", &b ); p = binary_search( a, a + 10, b ); for( q = a + 10; q != p; --q ) *q = q[-1]; *p = b; for( p = a; p != a + 11; ++p ) printf( "%d ", *p ); return 0; } 第二个,单链表查找删除: #include <stdio.h> #include <stdlib.h> typedef struct _list { int val; struct _list* next; } *node, list; node insert( node* head, node pos, int val ) { node tmp; tmp = ( node )malloc( sizeof( list ) ); tmp->val = val; tmp->next = pos ? pos->next : *head; if ( pos ) { pos->next = tmp; } else { *head = tmp; } return tmp; } node find( node head, int n ) { if ( !head ) return null; while ( head && head->val != n ) { head = head->next; } return head; } node create( int* beg, int* end ) { node head, t; head = t = null; while ( beg != end ) { t = insert( &head, t, *beg++ ); } return head; } void remove( node* head, node n ) { node prev, next; prev = next = *head; while ( next != n ) { prev = next; next = next->next; } if ( prev == *head ) { *head = next->next; } else { prev->next = next->next; } free( next ); } void print( node head ) { while ( head ) { printf( "%d ", head->val ); head = head->next; } putchar( '\n' ); } int main() { int a[] = { 6,1,3,9,2,8,5,0,7,4 }; int n; node head, pos; head = create( a, a + 10 ); print( head ); printf( "plz enter a num:" ); scanf( "%d", &n ); while( ( pos = find( head, n ) ) != null ) { remove( &head, pos ); } printf( "after delete all node with value %d:\n", n ); print( head ); return 0; }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯