| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 586 人关注过本帖
标题:链表 交换节点问题 能用中间变量直接交换吗?
只看楼主 加入收藏
sun004715
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2010-10-30
结帖率:100%
收藏
 问题点数:0 回复次数:0 
链表 交换节点问题 能用中间变量直接交换吗?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NUM 4

typedef struct student
{
    char name[10];
    int  num;
    struct student *prev;
    struct student *next;
}NODE, *PNODE;

struct student *creatInode(struct student *pHead);
void removeInode(struct student *pHead);
void InsertInode(PNODE pHead, NODE *Inode);
void traverse_list(PNODE pHead);
struct student *pHead = NULL;

int main(void)
{
    int i = NUM-1;
    NODE a[NUM] = {{"zhang", 1}, {"li", 3}, {"wu", 2}, {"xu", 4}};
     PNODE studentInfo =(PNODE)malloc(sizeof(NODE));

    pHead = creatInode(studentInfo);

       for (; i>=0; i--)
    {
        InsertInode(pHead, &a[i]);
    }
     traverse_list(pHead);
     removeInode(a);//按学号 排序

    traverse_list(pHead);
    return 0;
}

PNODE creatInode(PNODE pHead)
{
    pHead = (PNODE)malloc(sizeof(NODE));
    if (pHead == NULL)
    {
        printf("动态内存分配失败,程序中止!\n");
        exit(-1);
    }

    pHead->next = NULL;
    return pHead;
}

void InsertInode(PNODE pHead, PNODE Inode)
{
    if (!Inode)
    {
        printf("malloc error");
        exit (-1);
    }

    if(pHead->next != NULL)
    {
        pHead->next->prev = Inode;
        Inode->next = pHead->next;
        pHead->next = Inode;
        Inode->prev = pHead;
    }
    else
    {
                Inode->next = pHead->next;
                pHead->next = Inode;
                Inode->prev = pHead;
    }
}

void removeInode(NODE *pHead)
{
    int i = 0;
    int j = 0;
    PNODE temp = (PNODE)malloc(sizeof(NODE));
    for(; i<NUM; i++)
    {
        for(j=i+1; j<NUM; j++)
        {
            if (pHead[i].num > pHead[j].num)
            {
                *temp = pHead[i];
                pHead[i] = pHead[j];
                pHead[j] = *temp;
                free(temp);
             }
        }
    }
    for (i=0; i<NUM; i++)
    {
        printf("%d\n", pHead[i].num);
    }
}

void traverse_list(PNODE pHead)
{
    PNODE p;
    p = pHead->next;
    if (NULL == p)
    {
       printf("链表为空!\n");
    }
    while(NULL != p)
    {
        printf("name :%s  num :%d \n",p->name,p->num);
        p = p->next;
    }
}





在removeInode()函数里  能那样直接交换节点吗?  如果不能又为什么呢?
搜索更多相关主题的帖子: 链表 变量 节点 
2010-11-01 21:48
快速回复:链表 交换节点问题 能用中间变量直接交换吗?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014350 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved