0%

代码随想录第九天

链表-两两交换链表中的节点

题目链接

今天试了一下python编程,还是得慢慢把python熟练起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct ListNode* swapPairs(struct ListNode* head){
typedef struct ListNode ListNode;
ListNode *dummyNode = (ListNode *)malloc(sizeof(ListNode));
dummyNode->next = head; //后面好返回值
struct ListNode* cur = dummyNode;
while(cur->next && cur->next->next ){
struct ListNode* tmp;
struct ListNode* tmp1;
tmp = cur->next;
tmp1 = cur->next->next->next;//保留中途变换的时候会没有被指向的两个值
cur->next = cur->next->next;
cur->next->next = tmp;
cur->next->next->next = tmp1;
cur = cur->next->next;

}

return dummyNode->next;

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummyNode = ListNode(next=head)
cur = dummyNode

while cur.next and cur.next.next:
left = cur.next
right = cur.next.next

left.next = right.next
right.next = left
cur.next = right

cur = cur.next.next
return dummyNode.next