看完题结论就是:
链表题我是害怕的,很容易被它绕晕,还伴随着递归
嗯
画图,一定要画图。
给定一单链表A1->A2->A3->......->AN, 转换为A2->A1->A4->A3->.....->AN-1(如果N是偶数),
转换为A1->A3->A2->A5->A4->....->AN(如果N是奇数),要求是只能便利一遍链表。
First Thinking:
考虑的是如果N为偶数
构建的是带头结点的链表,参见上篇日志关于链表
- /*
- 针对有偶数位的带头结点的链表,采用递归
- */
- Left* ReserveEven(Left *node)
- {
- Left *temp = node->next;
- if(temp->next != NULL)
- {
- Left *p = temp->next;
- temp->next = node;
- node->next = ReserveEven(p);
- return temp;
- }
- temp->next = node;
- node->next = NULL;
- return temp;
- }
- /*
- 针对有偶数位的带头结点的链表,不用递归
- */
- Left* ReserveEven2(Left *node)
- {
- Left *head = node->next;
- while(node->next->next != NULL)
- {
- Left *next = node->next;
- Left *tmp = next->next;
- next->next = node;
- node->next = tmp->next;
- node = tmp;
- }
- node->next->next = node;
- node->next = NULL;
- return head;
- }
---------------------------------------------------------------------------
wks做法
1. 偶数个
如1->2->3->4传入时,调用vswap_inner后
*pp_head指向2->1->4->3,
*dangling指向NULL
2. 奇数个
如1->2->3->4->5传入时,调用vswap_inner后
*pp_head指向2->1->4->3,
*dangling指向1->...
所以需要在 vswap(Node** pp_head)函数中进行判断even否,如果为奇数,需要将
dangling->next = *pp_head;
*pp_head = dangling;
- #include <stdio.h>
- #include <stdlib.h>
- typedef int BOOL;
- #define FALSE (0)
- #define TRUE (!FALSE)
- typedef struct _Node Node;
- struct _Node {
- int data;
- Node* next;
- };
- Node* node_new(int data, Node* next);
- void node_seq_print(Node* node);
- // pp: input as the current head node
- // dangling: output only
- // output as the even point
- BOOL vswap_inner(Node** pp, Node** dangling) {
- if(*pp==NULL) {
- return TRUE;
- } else {
- Node* first = *pp;
- Node* rest = first->next;
- Node* ndangling;
- BOOL even = vswap_inner(&rest,&ndangling);
- if(even) {
- *pp=rest;
- *dangling=first;
- return FALSE;
- } else {
- ndangling->next = first;
- first->next = rest;
- *pp=ndangling;
- //*dangling=NULL; // Not useful
- return TRUE;
- }
- }
- }
- void vswap(Node** pp_head) {
- Node *dangling = NULL;
- BOOL even = vswap_inner(pp_head,&dangling);
- if(!even) {
- dangling->next = *pp_head;
- *pp_head=dangling;
- }
- }
- int main() {
- Node *node = node_new(1,
- node_new(2,
- node_new(3,
- node_new(4,
- node_new(5, NULL)
- ))));
- Node *node2 = node_new(1,
- node_new(2,
- node_new(3,
- node_new(4, NULL)
- )));
- vswap(&node);
- vswap(&node2);
- node_seq_print(node);
- node_seq_print(node2);
- return 0;
- }
- Node* node_new(int data, Node* next) {
- Node* node = (Node*)(malloc(sizeof(Node)));
- node->data=data;
- node->next=next;
- return node;
- }
- void node_free(Node* node) {
- free(node);
- }
- void node_seq_print(Node* node) {
- if(node==NULL) {
- printf("/n");
- } else {
- printf("%d ",node->data);
- node_seq_print(node->next);
- }
- }
转自:http://blog.youkuaiyun.com/jeiwt/archive/2009/12/18/5032145.aspx