链表 交换节点问题 能用中间变量直接交换吗?
#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()函数里 能那样直接交换节点吗? 如果不能又为什么呢?