zoukankan      html  css  js  c++  java
  • 单链表就地反转

      实现一个函数:void reverse(struct list_node *head)在尽量不借助辅助变量的情况下,实现任意长度单链表(不考虑内存限制)的反转(or 逆序)。

    struct list_node{
    	int val;
    	struct list_node *next;
    };
    
    struct list{
    	struct list_node *head;	
    	struct list_node *tail;
    };
    
    void reverse(struct list_node *head)
    {
    
    }
    int main()
    {
        struct list list = {NULL, NULL};
        struct list_node *p = NULL;
        /*init list*/
        /*打印反转前各节点的值*/
        reverse(list.head);
        p = list.head;
        list.head = list.tail;
        list.tail = p;
        /*打印反转后各节点的值*/
    }
    

      代码实现:

    #include <stdio.h>
    
    struct list_node{
    	int index;
    	struct list_node *next;
    };
    struct list
    {
    	struct list_node *head;
    	struct list_node *tail;
    };
    void reverse(struct list_node *head)
    {
    	if(NULL == head|| NULL == head->next )
    	    return;
    	reverse(head->next);
    	head->next->next = head;
    	head->next = NULL;
    }
    int main()
    {
    	int i = 0;
    	struct list list = {NULL, NULL};
    	struct list_node node[10] = {0};
    	struct list_node *p;
    	for(i = 0; i < 9; i++)
    	{
    		node[i].index = i;
    		node[i].next = &node[i + 1];
    	}
    	node[9].index = 9;
    	list.head = node;
    	list.tail = node + 9;
    	
    	reverse(list.head);
    	for(p = list.tail; p; p=p->next)
    	{
    		printf("%d 
    ",p->index);
    	}
            return 0;  
    }    
    

      

  • 相关阅读:
    [HAOI2008]糖果传递
    [HAOI2008]木棍分割
    [HAOI2008]硬币购物
    [ZJOI2008]泡泡堂
    [JSOI2007]建筑抢修
    [JSOI2007]麻将
    [Note]prufer
    [BZOJ3275]Number
    [POI2014]RAJ-Rally
    [JSOI2010]快递服务
  • 原文地址:https://www.cnblogs.com/chars/p/4987903.html
Copyright © 2011-2022 走看看