给定带有表头结点的单向链表,编写一个函数,将链表中偶数序号的数据节点移到链尾。
链表节点的结构定义:
typedef struct numLink
{
int no;
struct numLink *next;
}NODE;
所编写函数的原型:void movenode( NODE *head)
其中:参数head 是单向链表的头指针。
输入:节点数目
输出:处理后的结果
说明:仅提交函数 void movenode( NODE *head) 即可。
预设代码
前置代码
- /* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct numLink
- {
- int no;
- struct numLink *next;
- }NODE;
- void movenode( NODE *head);
- void SetLink( NODE *h, int n )
- {
- NODE *p=NULL, *q=NULL;
- int i;
- for( i=0; i<n; i++)
- {
- p = (NODE *)malloc(sizeof(NODE));
- p->no = i+1;
- p->next = NULL;
- if( h->next == NULL )
- {
- h->next = p;
- q = p;
- }
- else
- {
- q->next = p;
- q = q->next;
- }
- }
- return;
- }
- int main( )
- {
- int n;
- NODE *head=NULL, *q=NULL;
- scanf("%d",&n);
- head = (NODE *)malloc(sizeof(NODE));
- head->no = -1;
- head->next = NULL;
- SetLink( head, n );
- movenode( head );
- q = head;
- while (q->next){
- printf("%d ",q->next->no);
- q = q->next;
- }
- printf("\n");
- system("pause");
- return 0;
- }
- /* PRESET CODE END - NEVER TOUCH CODE ABOVE */
/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */ #include <stdio.h> #include <stdlib.h> typedef struct numLink { int no; struct numLink *next; } NODE; void movenode( NODE *head) { NODE *p, *q, *last; p = head->next; last = head; int count = 0; while (last->next != NULL) { last = last->next; count ++; } for(int i=0;i < count/2 && count != 2; i ++) { q = p->next; if (q->no % 2 == 0 ) { p->next = q->next; q->next = NULL; last->next = q; last = last->next; } p = p->next; } } void SetLink( NODE *h, int n ) { NODE *p = NULL, *q = NULL; int i; for ( i = 0; i < n; i++) { p = (NODE *)malloc(sizeof(NODE)); p->no = i + 1; p->next = NULL; if ( h->next == NULL ) { h->next = p; q = p; } else { q->next = p; q = q->next; } } return; } int main( ) { int n; NODE *head = NULL, *q = NULL; scanf("%d", &n); head = (NODE *)malloc(sizeof(NODE)); head->no = -1; head->next = NULL; SetLink( head, n ); movenode( head ); q = head; while (q->next) { printf("%d ", q->next->no); q = q->next; } printf("\n"); system("pause"); return 0; } /* PRESET CODE END - NEVER TOUCH CODE ABOVE */