我在链接列表中交换相邻节点时遇到问题。
对于ex:输入:1-> 2-> 3-> 4-> 5-> null 输出:2-> 1-> 4-> 3-> 5->无效
bool swapAdjacent(node** head)
{
//1->2->3->4->null
//2->1->4->3->null
if(head==NULL)
return 0;
node* current = *head;
*head = (*head)->next ;
node* prev = NULL;
cout<<"head val "<<(*head)->data <<endl;
node* temp;
while( current!=NULL&¤t->next!=NULL)
{
temp = current->next ; //1s pointer points to 2
current->next = temp->next ; // 1s pointer point to 3
temp ->next = current; //2s pointer shud point to 1
prev = current;
current = current->next ;
//cout<<"data " <<current->data <<endl;
if(current!=NULL)
prev->next = current->next ;
}
return 1;
}
只要奇数没有节点,我的代码就无法运行。如何解决这个问题?
答案 0 :(得分:6)
为什么这么复杂?
int swapAdjacent(node** head) {
if (!*head || !(*head)->next)
return 0;
node* const sw = (*head)->next;
(*head)->next = sw->next;
sw->next = *head;
*head = sw;
swapAdjacent(&(sw->next->next));
return 1;
}
编辑:更改了返回值。
答案 1 :(得分:0)
我不知道您的代码有什么问题,但我会通过循环显示列表的状态来接近它:
void printList(node* head)
{
int cntr = 1;
while (head != NULL)
{
printf("(Node: %d. Name: %s) --> ", cntr, head->name);
head = head->next;
}
}
为此,请确保每个节点都有name
,设置为“1”,“2”等。
然后打印每个传递列表的状态,甚至每一步!
你应该看看出了什么问题。
答案 2 :(得分:0)
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
struct s_sll
{
int info;
struct s_sll *link;
};
typedef s_sll node;
class sll
{
public:
static int cou;
node *first;
sll()
{
first=NULL;
cou++;
}
node*create_node(int val);
node*del_val();
void disp();
void swap_adjcent();
~sll()
{
delete first;
cou--;
}
};
void disp_all(sll **);
void despose(sll **);
int sll::cou=0;
void sll::swap_adjcent()
{
node *temp,*a,*b;
a=first;
b=a->link;
temp=b->link;
a->link=temp->link;
b->link=a;
first=b;
while(b!=NULL)
{
a=temp;
b=temp->link;
temp=b->link;
if(temp->link!=NULL)
{
a->link=temp->link;
b->link=a;
a=temp->link;
}
else
{
a->link=temp;
b->link=a;
}
}
delete temp;
}
node* sll::create_node(int val)
{
node *save,*temp;
temp = new s_sll;
temp->info=val;
temp->link=NULL;
if(first==NULL)
first=temp;
else
{
save=first;
while(save->link!=NULL)
save=save->link;
save->link=temp;
}
return first;
}
答案 3 :(得分:0)
public static node adjacent_reversal(node head)
{
node temp = null;
if(head == null)
return null;
if(head.next == null)
{
head.next = null;
return head;
}
temp = adjacent_reversal(head.next.next);
node temp1 = head.next;
head.next.next = head;
head.next = temp;
return temp1;
}
答案 4 :(得分:0)
并在循环中迭代它,直到p2指向null ... 和循环增量应
p1=(p1->next)->next;
p2=(p2->next)->next;
//swap the node pointed by these two pointers ..
这会很好用..