之前在网上看到一道题,如何将一个链表反转,当时没有实践做,现在来写一下。有些东西不当时写下来过段时间就会容易忘掉
首先我们先来创建一个单链表,这里我们选择尾插法来构建
struct node
{
int num;
struct node * next;
};
int main()
{
node *head;
node *s, *p, *r;
head = (node *)malloc(sizeof(node));
r = head;
int num_list[10] = {0,1,2,3,4,5,6,7,8,9};
for (int i=0;i<10;i++)
{
s = (node *)malloc(sizeof(node));
s->num = num_list[i];
r->next = s;
r = s;
}
r->next = NULL;
}
printf("反转前:");
while (curr!=NULL)
{
printf("%d ", curr->num);
curr=curr->next;
}
接下来进行反转。反转的时候需要3个指针。一个指针用来指向反转后的链表,命名为newl,一个指针用来记录当前节点,命名为curr,一个指针用来记录当前节点的下一个节点。命名为pnext,这是因为你在将当前节点反转之后,就会失去下一个节点,所以需要提前进行记录一下。下面来看代码
node *curr = head->next, *pnext;
node *newl = (node *)malloc(sizeof(node));
newl->next = NULL;
curr = head->next;
while (curr!= NULL)
{
pnext = (node *)malloc(sizeof(node));
pnext = curr->next;
curr->next = newl->next;
newl->next = curr;
curr = pnext;
}
pnext = newl->next;
printf("反转后:");
while (pnext!=NULL)
{
printf("%d ", pnext->num);
pnext=pnext->next;
}
最后我们看一下输出结果
不过这样进行反转会将原链表进行损坏,如果不想原链表损坏,可以直接开辟一个新的链表,这个方法我会在以后补充进来。
来更新了,不过是用python写的
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def ReverseList(pHead):
# write code here
p, q, r = pHead, None, None
while p is not None:
q = p.next
p.next = r
r = p
p = q
return r