2种头插法的写法
struct node_t* insertHead( struct node_t *h, struct node_t *n )
{
n->next = h;
return n;
}
void insertHead1( struct node_t **h, struct node_t *n )
{
n->next = *h;
*h = n;
}
2种尾插法的写法
struct node_t *insertTail( struct node_t *h , struct node_t *n )
{
if( h == NULL ){
return n;
}
struct node_t *p = h;
while( p->next != NULL ){
p = p->next;
}
p->next = n;
return h;
}
void insertTail1( struct node_t **h, struct node_t *n )
{
while( *h ){
h = &((*h)->next);
}
*h = n;
}
摘取想查找值的结点,并且形成新链表
struct node_t *findNode( struct node_t **h, int goal )
{
struct node_t *newlist = NULL;
while( (*h)->val == goal ){
struct node_t *tmp = *h;
*h = (*h)->next;
tmp->next = NULL;
insertTail1( &newlist, tmp );
}
struct node_t *t = *h;
while( t->next ){
struct node_t *p = t->next;
if( p->val == goal ){
struct node_t *tmp = p;
t->next = p->next;
tmp->next = NULL;
insertTail1( &newlist, tmp );
}else{
t = t->next;
}
}
return newlist;
}
总体程序
#include <stdio.h>
#include <stdlib.h>
struct node_t{
int idx;
int val;
struct node_t *next;
};
void showList( struct node_t *h )
{
printf("++++++++++++++++++++++++++++++\n");
while( h ){
printf("h->idx = %d, h->val = %d\n", h->idx, h->val );
h = h->next;
}
}
struct node_t* insertHead( struct node_t *h, struct node_t *n )
{
n->next = h;
return n;
}
void insertHead1( struct node_t **h, struct node_t *n )
{
n->next = *h;
*h = n;
}
struct node_t *insertTail( struct node_t *h , struct node_t *n )
{
if( h == NULL ){
return n;
}
struct node_t *p = h;
while( p->next != NULL ){
p = p->next;
}
p->next = n;
return h;
}
void insertTail1( struct node_t **h, struct node_t *n )
{
while( *h ){
h = &((*h)->next);
}
*h = n;
}
struct node_t *findNode( struct node_t **h, int goal )
{
struct node_t *newlist = NULL;
while( (*h)->val == goal ){
struct node_t *tmp = *h;
*h = (*h)->next;
tmp->next = NULL;
insertTail1( &newlist, tmp );
}
struct node_t *t = *h;
while( t->next ){
struct node_t *p = t->next;
if( p->val == goal ){
struct node_t *tmp = p;
t->next = p->next;
tmp->next = NULL;
insertTail1( &newlist, tmp );
}else{
t = t->next;
}
}
return newlist;
}
int main()
{
int arr[] = {10,10,9,8,5,20,10,10,30,20,10,10};
struct node_t *head = NULL;
int i = 0;
struct node_t *newnode = NULL;
while( i < sizeof(arr)/sizeof(int) ){
newnode = malloc( sizeof(struct node_t) );
newnode->val = arr[i];
newnode->idx = i;
newnode->next = NULL;
insertTail1( &head, newnode );
i++;
}
struct node_t *newlist = findNode( &head, 10 );
showList( head );
showList( newlist );
}